<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧树形结构 -->
      <el-col :span="6" :xs="24">
        <div class="tree-container">
          <el-tree
            :data="factoryTree"
            :props="defaultProps"
            :expand-on-click-node="false"
            ref="tree"
            highlight-current
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse"
            node-key="id"
            :default-expanded-keys="defaultExpandedKeys"
            class="factory-tree"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>
                <i v-if="data.type === 'root'" class="el-icon-s-fold"></i>
                <i v-else-if="data.type === 'factory'" class="el-icon-document"></i>
                <i v-else-if="data.type === 'workshop'" class="el-icon-house"></i>
                <i v-else-if="data.type === 'line'" class="el-icon-s-operation"></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧数据表格 -->
      <el-col :span="18" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
          <el-form-item>
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入关键词搜索"
              clearable
              size="small"
              style="width: 300px"
              @keyup.enter.native="handleQuery"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleQuery" />
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleQuery">搜索</el-button>
            <el-button plain @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
        </el-row>

        <!-- 生产线详情表格 -->
        <el-table
          v-if="currentNodeType === 'line'"
          v-loading="loading"
          :data="productionLineList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="创建时间" align="center" prop="create_time" width="180">
            <template slot-scope="scope">
              {{ scope.row.create_time ? scope.row.create_time.split('T')[0] : '' }}
            </template>
          </el-table-column>
          <el-table-column label="生产线编号" align="center" prop="line_code" />
          <el-table-column label="生产线名称" align="center" prop="line_name" :show-overflow-tooltip="true" />
          <el-table-column label="所属车间" align="center" prop="workshop_name" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.workshop_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="所属工厂" align="center" prop="factory_name" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.factory_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.remarks || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="create_by">
            <template slot-scope="scope">
              {{ scope.row.create_by || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width operation-column" width="120">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" class="blue-text">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" class="red-text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 工位详情表格 -->
        <el-table
          v-else-if="currentNodeType === 'workstation'"
          v-loading="loading"
          :data="workstationList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="创建时间" align="center" prop="create_time" width="180">
            <template slot-scope="scope">
              {{ scope.row.create_time ? scope.row.create_time.split('T')[0] : '' }}
            </template>
          </el-table-column>
          <el-table-column label="工位编号" align="center" prop="station_code" />
          <el-table-column label="工位名称" align="center" prop="station_name" :show-overflow-tooltip="true" />
          <el-table-column label="所属生产线" align="center" prop="production_line_name" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.production_line_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="所属车间" align="center" prop="workshop_name" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.workshop_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="所属工厂" align="center" prop="factory_name" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.factory_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.remarks || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="create_by">
            <template slot-scope="scope">
              {{ scope.row.create_by || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width operation-column" width="120">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" class="blue-text">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" class="red-text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 其他节点类型的表格 -->
        <el-table
          v-else
          v-loading="loading"
          :data="factoryList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          
          <!-- 根据当前节点类型动态显示不同的列 -->
          <template v-if="currentNodeType === 'factory'">
            <el-table-column label="创建时间" align="center" prop="create_time" width="180">
              <template slot-scope="scope">
                {{ scope.row.create_time ? scope.row.create_time.split(' ')[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column label="工厂编号" align="center" prop="factory_code" />
            <el-table-column label="工厂名称" align="center" prop="factory_name" :show-overflow-tooltip="true" />
            <el-table-column label="工厂地址" align="center" prop="factory_address" :show-overflow-tooltip="true" />
            <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ scope.row.remarks || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="创建者" align="center" prop="create_by" class-name="creator-column">
              <template slot-scope="scope">
                {{ scope.row.create_by || '-' }}
              </template>
            </el-table-column>
            <!-- 隐藏列，用于调试 -->
            <el-table-column label="ID" align="center" prop="factory_id" v-if="false">
              <template slot-scope="scope">
                {{ scope.row.factory_id || '-' }}
              </template>
            </el-table-column>
          </template>
          
          <template v-else-if="currentNodeType === 'workshop'">
            <el-table-column label="创建时间" align="center" prop="create_time" width="180">
              <template slot-scope="scope">
                {{ scope.row.create_time ? scope.row.create_time.split('T')[0] : '' }}
              </template>
            </el-table-column>
            <el-table-column label="车间编号" align="center" prop="workshop_code" />
            <el-table-column label="车间名称" align="center" prop="workshop_name" :show-overflow-tooltip="true" />
            <el-table-column label="所属工厂" align="center" prop="factory_name" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ scope.row.factory_name || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ scope.row.remarks || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="create_by" class-name="creator-column">
              <template slot-scope="scope">
                {{ scope.row.create_by || '-' }}
              </template>
            </el-table-column>
          </template>
          
          <!-- 操作列，始终放在最后 -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width operation-column" width="120">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                type="text" 
                icon="el-icon-edit" 
                @click="handleUpdate(scope.row)" 
                class="blue-text"
                :disabled="!scope.row.factory_id && currentNodeType === 'factory'">修改</el-button>
              <el-button 
                size="mini" 
                type="text" 
                icon="el-icon-delete" 
                @click="handleDelete(scope.row)" 
                class="red-text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改工厂对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- 工厂表单 -->
      <el-form v-if="formType === 'factory'" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="工厂编号" prop="factory_code">
          <el-input 
            v-model="form.factory_code" 
            placeholder="请输入工厂编号" 
            disabled
            class="factory-code-input">
            <el-button 
              v-if="title === '新增工厂'"
              slot="append" 
              icon="el-icon-refresh" 
              @click="handleGetAutoNumber">
              自动编号
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="工厂名称" prop="factory_name">
          <el-input v-model="form.factory_name" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="工厂地址" prop="factory_address">
          <el-input v-model="form.factory_address" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <!-- 车间表单 -->
      <el-form v-else-if="formType === 'workshop'" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属工厂" prop="factory_id" required>
          <el-select v-model="form.factory_id" placeholder="请选择" disabled>
            <el-option
              v-if="form.factory_id"
              :key="form.factory_id"
              :label="factoryNameMap[form.factory_id] || currentNode.label || '未知工厂'"
              :value="form.factory_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车间编号" prop="workshop_code" required>
          <el-input 
            v-model="form.workshop_code" 
            placeholder="请输入车间编号" 
            disabled
            class="workshop-code-input">
            <el-button 
              v-if="title === '新增车间'"
              slot="append" 
              icon="el-icon-refresh" 
              @click="handleGetAutoWorkshopNumber">
              自动编号
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="车间名称" prop="workshop_name" required>
          <el-input v-model="form.workshop_name" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <!-- 生产线表单 -->
      <el-form v-else-if="formType === 'line'" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属工厂" prop="factory_id" required>
          <el-select v-model="form.factory_id" placeholder="请选择" disabled>
            <el-option
              :key="currentNode.factoryId"
              :label="factoryNameMap[currentNode.factoryId] || '未知工厂'"
              :value="currentNode.factoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属车间" prop="workshop_id" required>
          <el-select v-model="form.workshop_id" placeholder="请选择" disabled>
            <el-option
              :key="currentNode.workshopId"
              :label="currentNode.label"
              :value="currentNode.workshopId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产线编号" prop="line_code" required>
          <el-input 
            v-model="form.line_code" 
            placeholder="请输入生产线编号" 
            disabled
            class="line-code-input">
            <el-button 
              v-if="title === '新增生产线'"
              slot="append" 
              icon="el-icon-refresh" 
              @click="handleGetAutoLineNumber">
              自动编号
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="生产线名称" prop="line_name" required>
          <el-input v-model="form.line_name" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <!-- 工位表单 -->
      <el-form v-else-if="formType === 'workstation'" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属工厂" prop="factory_id" required>
          <el-select v-model="form.factory_id" placeholder="请选择" disabled>
            <el-option
              :key="currentNode.factoryId"
              :label="factoryNameMap[currentNode.factoryId] || '未知工厂'"
              :value="currentNode.factoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属车间" prop="workshop_id" required>
          <el-select v-model="form.workshop_id" placeholder="请选择" disabled>
            <el-option
              :key="currentNode.workshopId"
              :label="workshopNameMap[currentNode.workshopId] || '未知车间'"
              :value="currentNode.workshopId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属生产线" prop="line_id" required>
          <el-select v-model="form.line_id" placeholder="请选择" disabled>
            <el-option
              :key="currentNode.lineId"
              :label="currentNode.label"
              :value="currentNode.lineId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工位编号" prop="station_code" required>
          <el-input 
            v-model="form.station_code" 
            placeholder="请输入工位编号" 
            disabled
            class="station-code-input">
            <el-button 
              v-if="title === '新增工位'"
              slot="append" 
              icon="el-icon-refresh" 
              @click="handleGetAutoStationNumber">
              自动编号
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="工位名称" prop="station_name" required>
          <el-input v-model="form.station_name" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listFactory, getFactory, addFactory, updateFactory, delFactory,
  listWorkshop, getWorkshop, addWorkshop, updateWorkshop, delWorkshop,
  listProductionLine, getProductionLine, addProductionLine, updateProductionLine, delProductionLine,
  listWorkstation, getWorkstation, addWorkstation, updateWorkstation, delWorkstation
} from "@/api/basic/factory";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
// 确保导入了正确的API方法

export default {
  name: "FactoryModeling",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 防止重复请求的标志
      isLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工厂表格数据
      factoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: "",
        factoryName: "",
        factoryId: "",
        factoryAddress: "",
      },
      // 表单参数
      form: {},
      // 表单类型 (factory, workshop, line, workstation)
      formType: 'factory',
      // 表单校验
      rules: {
        // 工厂表单验证规则
        factory_name: [
          { required: true, message: "工厂名称不能为空", trigger: "blur" }
        ],
        factory_code: [
          { required: true, message: "工厂编号不能为空", trigger: "blur" }
        ],
        // 车间表单验证规则
        workshop_code: [
          { required: true, message: "车间编号不能为空", trigger: "blur" }
        ],
        workshop_name: [
          { required: true, message: "车间名称不能为空", trigger: "blur" }
        ],
        // 生产线表单验证规则
        line_code: [
          { required: true, message: "生产线编号不能为空", trigger: "blur" }
        ],
        line_name: [
          { required: true, message: "生产线名称不能为空", trigger: "blur" }
        ],
        // 工位表单验证规则
        station_code: [
          { required: true, message: "工位编号不能为空", trigger: "blur" }
        ],
        station_name: [
          { required: true, message: "工位名称不能为空", trigger: "blur" }
        ]
      },

      // 树形数据 - 包含全部根节点
      factoryTree: [
        {
          id: 'root',
          label: '全部',
          type: 'root',
          isLeaf: false
        }
      ],
      // 默认展开的节点key
      defaultExpandedKeys: ['root'],
      // 树形配置
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      // 当前选中的节点
      currentNode: null,
      // 节点类型 (root, factory, workshop, line, workstation)
      currentNodeType: "root",
      // 生产线详情表格数据
      productionLineList: [],
      // 工位详情表格数据
      workstationList: [],
      // 工厂ID到名称的映射
      factoryNameMap: {},
      // 车间ID到名称的映射
      workshopNameMap: {},
    };
  },
  created() {
    // 初始化加载 - 使用setTimeout避免同时发起多个请求
    setTimeout(() => {
      this.init();
    }, 100);
  },
  mounted() {
    // 不在mounted中调用selectRootNode，避免重复加载
    // 将由init方法完成后调用
  },
  methods: {
    // 初始化方法
    async init() {
      try {
        // 显示加载状态
        this.loading = true;
        
        // 先设置当前节点类型为工厂，避免表格渲染问题
        this.currentNodeType = 'factory';
        
        // 顺序加载数据，避免并发请求
        console.log("开始加载工厂名称映射...");
        const factoryMapResult = await this.loadFactoryNameMap();
        
        // 检查工厂映射是否成功加载
        if (!factoryMapResult || Object.keys(factoryMapResult).length === 0) {
          console.warn("工厂名称映射加载失败或为空，重试...");
          // 重试一次
          await this.loadFactoryNameMap();
        }
        
        console.log("开始加载车间名称映射...");
        await this.loadWorkshopNameMap();
        
        console.log("开始初始化树结构...");
        // 使用延迟加载树结构，先只加载工厂节点，后续按需加载子节点
        await this.initTreeWithLazyLoading();
        
        // 检查树结构初始化后是否有工厂节点
        if (this.factoryTree[0]?.children?.length === 0) {
          console.warn("树结构初始化后没有工厂节点，重新尝试加载工厂数据...");
          await this.loadFactoryNameMap();
          await this.initTreeWithLazyLoading();
        }
        
        // 完成初始化后，选择根节点显示数据
        console.log("初始化完成，选择根节点...");
        this.selectRootNode();
        
      } catch (error) {
        console.error("初始化失败:", error);
        this.$message.error("初始化失败，请刷新页面重试");
        this.loading = false;
      }
    },
    
    // 延迟加载树结构方法
    async initTreeWithLazyLoading() {
      this.loading = true;
      console.time('initTree'); // 开始计时树初始化
      try {
        // 重置默认展开的节点
        this.defaultExpandedKeys = ['root'];
        
        // 使用已加载的工厂映射数据创建工厂节点
        const factoryIds = Object.keys(this.factoryNameMap);
        const factoryNames = Object.values(this.factoryNameMap);
        
        console.log(`准备构建树结构，使用${factoryIds.length}个工厂节点`);
        
        // 预先估算需要的数组大小，优化内存分配
        const factoryNodes = new Array(factoryIds.length);
        
                  // 如果没有工厂数据，尝试重新加载
          if (factoryIds.length === 0) {
            console.log("工厂映射为空，尝试重新加载工厂数据");
            try {
              const factoryRes = await listFactory({ pageSize: 100, pageNum: 1 });
              const factories = factoryRes.rows || [];
              
              // 更新工厂名称映射
              const map = {};
              factories.forEach(factory => {
                if (factory && factory.factory_id) {
                  map[factory.factory_id] = factory.factory_name || '未命名工厂';
                }
              });
              this.factoryNameMap = map;
              console.log("工厂名称映射已更新, 共", Object.keys(map).length, "个工厂");
              
              // 使用更新后的工厂ID和名称
              const factoryIds = Object.keys(this.factoryNameMap);
              const factoryNames = Object.values(this.factoryNameMap);
              
              // 处理每个工厂
              for (const factory of factories) {
                if (!factory.factory_id) continue;
                
                const factoryNode = {
                  id: factory.factory_id,
                  label: factory.factory_name || '未命名工厂',
                  type: 'factory',
                  factoryId: factory.factory_id,
                  factory_id: factory.factory_id,
                  children: [] // 初始为空数组，表示可以展开
                };
                
                // 为每个工厂加载车间
                await this.loadWorkshopsForFactory(factoryNode);
                
                factoryNodes.push(factoryNode);
                
                // 将工厂ID添加到默认展开的节点中
                this.defaultExpandedKeys.push(factory.factory_id);
                
                // 只展开前两个工厂，避免过多展开
                if (this.defaultExpandedKeys.length > 3) break;
              }
            } catch (error) {
              console.error("重新加载工厂数据失败:", error);
            }
          } else {
          // 使用已有的工厂映射数据
          // 创建一组promises以便并行执行
          const promises = [];
          
          for (let i = 0; i < factoryIds.length; i++) {
            const factoryId = factoryIds[i];
            const factoryName = factoryNames[i];
            
            // 创建工厂节点
            const factoryNode = {
              id: factoryId,
              label: factoryName || '未命名工厂',
              type: 'factory',
              factoryId: factoryId,
              factory_id: factoryId,
              children: [] // 初始为空数组，表示可以展开
            };
            
            // 直接将节点放入数组的对应位置
            factoryNodes[i] = factoryNode;
            
            // 添加到默认展开节点
            if (i < 2) { // 只展开前两个工厂
              this.defaultExpandedKeys.push(factoryId);
            }
            
            // 创建加载车间的Promise，但不立即等待它完成
            if (i < 5) { // 只预加载前5个工厂的车间，减轻初始负担
              const loadPromise = (async (node, idx) => {
                try {
                  await this.loadWorkshopsForFactory(node);
                  return idx; // 返回索引表示完成
                } catch (error) {
                  console.error(`预加载工厂[${node.label}]的车间失败:`, error);
                  return -1;
                }
              })(factoryNode, i);
              promises.push(loadPromise);
            }
          }
          
          // 并行等待前几个工厂的车间加载完成
          if (promises.length > 0) {
            try {
              await Promise.all(promises);
            } catch (error) {
              console.error("并行加载车间失败:", error);
            }
          }
        }
        
        // 过滤掉空节点
        const filteredNodes = factoryNodes.filter(node => node);
        
        // 更新根节点 - 如果当前树已存在且有相同结构，尝试保留现有树结构以减少重绘
        if (this.factoryTree && this.factoryTree.length > 0 && this.factoryTree[0].children) {
          // 只有在节点数量变化或者根节点不存在时才完全重建树
          if (this.factoryTree[0].children.length !== filteredNodes.length) {
            this.factoryTree[0].children = filteredNodes;
          } else {
            console.log("保留现有树结构，只更新子节点内容");
            // 通过引用更新现有节点内容，避免重建整个树结构
            for (let i = 0; i < filteredNodes.length; i++) {
              Object.assign(this.factoryTree[0].children[i] || {}, filteredNodes[i]);
            }
          }
        } else {
          // 首次创建或现有树无效时，完全重建树
          this.factoryTree = [
            {
              id: 'root',
              label: '全部',
              type: 'root',
              children: filteredNodes
            }
          ];
        }

        console.log("树初始化完成，共", filteredNodes.length, "个工厂节点");
        return this.factoryTree;
      } catch (error) {
        console.error('初始化树结构失败:', error);
        this.$message.error('加载数据失败，请刷新页面重试');
        // 确保至少有一个根节点
        this.factoryTree = [
          {
            id: 'root',
            label: '全部',
            type: 'root',
            children: []
          }
        ];
        return this.factoryTree;
      } finally {
        this.loading = false;
        console.timeEnd('initTree'); // 结束树初始化计时
      }
    },
    
    // 加载工厂名称映射
    async loadFactoryNameMap() {
      try {
        console.log("开始加载工厂名称映射，当前映射中有", Object.keys(this.factoryNameMap).length, "个工厂");
        
        // 如果已经有足够的工厂数据（超过50个），且不是在初始化阶段，则跳过重新加载
        // 这样可以避免不必要的API调用
        if (Object.keys(this.factoryNameMap).length > 50 && this.factoryTree && this.factoryTree.length > 0) {
          console.log("已有足够的工厂映射数据，跳过加载");
          return this.factoryNameMap;
        }
        
        console.time('loadFactoryMap'); // 开始计时
        
        // 使用较小的页面大小，避免加载过多数据
        const res = await listFactory({ 
          pageSize: 100,
          pageNum: 1
        });
        
        if (!res || !res.rows) {
          console.warn("工厂列表返回为空");
          // 如果当前已有映射数据，则保留
          if (Object.keys(this.factoryNameMap).length > 0) {
            console.log("保留现有映射数据");
            return this.factoryNameMap;
          }
          return {};
        }
        
        const factories = res.rows || [];
        
        // 优化：如果工厂数据与当前映射长度相同，检查是否有变化
        // 如果数据基本一致，则避免完全重建映射
        if (factories.length === Object.keys(this.factoryNameMap).length && 
            factories.length > 0 && Object.keys(this.factoryNameMap).length > 0) {
          
          // 检查前10个工厂是否一致，如果一致，假定数据未变更
          let unchanged = true;
          for (let i = 0; i < Math.min(10, factories.length); i++) {
            const factory = factories[i];
            if (factory && factory.factory_id) {
              if (this.factoryNameMap[factory.factory_id] !== (factory.factory_name || '未命名工厂')) {
                unchanged = false;
                break;
              }
            }
          }
          
          if (unchanged) {
            console.log("工厂映射数据未变化，跳过更新");
            console.timeEnd('loadFactoryMap');
            return this.factoryNameMap;
          }
        }
        
        console.log("从API获取到", factories.length, "个工厂");
        
        // 创建新映射
        const map = {};
        factories.forEach(factory => {
          if (factory && factory.factory_id) {
            map[factory.factory_id] = factory.factory_name || '未命名工厂';
          }
        });
        
        // 更新当前映射
        this.factoryNameMap = map;
        console.log("工厂名称映射加载完成, 共", Object.keys(map).length, "个工厂");
        console.timeEnd('loadFactoryMap');
        return map;
      } catch (error) {
        console.error("加载工厂名称映射失败:", error);
        // 如果当前已有映射数据，则保留
        if (Object.keys(this.factoryNameMap).length > 0) {
          console.log("出错时保留现有映射数据");
          return this.factoryNameMap;
        }
        this.factoryNameMap = {};
        return {};
      }
    },
    
    // 加载车间名称映射
    async loadWorkshopNameMap() {
      try {
        // 使用较小的页面大小，避免加载过多数据
        const res = await listWorkshop({ 
          pageSize: 100,
          pageNum: 1
        });
        
        if (!res || !res.rows) {
          console.warn("车间列表返回为空");
          return {};
        }
        
        const workshops = res.rows || [];
        const map = {};
        workshops.forEach(workshop => {
          if (workshop && workshop.workshop_id) {
            map[workshop.workshop_id] = workshop.workshop_name || '未命名车间';
          }
        });
        
        this.workshopNameMap = map;
        console.log("车间名称映射加载完成, 共", Object.keys(map).length, "个车间");
        return map;
      } catch (error) {
        console.error("加载车间名称映射失败:", error);
        this.workshopNameMap = {};
        return {};
      }
    },

    // 选中根节点
    selectRootNode() {
      // 先尝试直接加载工厂列表，不依赖树的点击事件
      this.currentNodeType = 'factory';
      this.getList();
      
      // 延迟执行树节点选中，确保树已经渲染完成
      setTimeout(() => {
        try {
          // 找到根节点并选中
          if (this.$refs.tree && this.factoryTree.length > 0) {
            const rootNode = this.factoryTree[0];
            this.$refs.tree.setCurrentKey(rootNode.id);
            console.log("自动选中根节点:", rootNode.label);
            
            // 设置当前节点，但不再触发handleNodeClick
            this.currentNode = rootNode;
          } else {
            console.warn("树组件未准备好或树数据为空");
          }
        } catch (error) {
          console.error("选中根节点失败:", error);
        }
      }, 500);
    },

    // 添加延迟执行工具方法
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    
    /** 查询工厂列表 */
    async getList() {
      // // 避免在短时间内重复加载
      // if (this.loading) {
      //   console.log("已有加载请求正在进行，跳过");
      //   return;
      // }
      
      // this.loading = true;
      // console.time('getList'); // 开始计时，测量性能
      
      try {
        // 提取查询参数中的工厂ID
        const factoryId = this.queryParams.factoryId || this.queryParams.factory_id;
        
        // 构建查询参数
        const query = {
          pageNum: this.queryParams.pageNum || 1,
          pageSize: this.queryParams.pageSize || 10
        };
        
        // 如果有关键词搜索
        if (this.queryParams.keyword) {
          query.keyword = this.queryParams.keyword;
        }
        
        // 如果是从树节点点击进入，可能已包含basicFactory对象
        if (factoryId) {
          query.factory_id = factoryId;
        }
        
        console.log("开始加载工厂列表，参数:", query);
        const response = await listFactory(query);
        
        // 判断响应是否有效
        if (!response || !response.rows) {
          console.warn("工厂列表返回无效");
          return;
        }
        
        // 优化数据处理 - 减少日志输出和不必要的操作
        const processedData = [];
        
        for (const factory of response.rows) {
          // 确定正确的字段映射
          const factoryId = factory.factory_id || factory.factoryId || null;
          const factoryCode = factory.factory_code || factory.factoryCode || factoryId || '';
          let remarks = factory.remarks || factory.remark || '';
          let createBy = factory.create_by || factory.createBy || factory.created_by || '-';
          
          // 如果数据显示在错误的位置，进行修正
          if (typeof remarks === 'string' && remarks.length <= 10 && 
              (remarks === 'admin' || remarks.startsWith('user'))) {
            // 可能是创建人字段被错误地映射到备注
            createBy = remarks;
            remarks = '';
          }
          
          // 添加处理后的数据
          processedData.push({
            ...factory,
            factory_id: factoryId,
            factory_code: factoryCode,
            remarks: remarks,
            create_by: createBy
          });
        }
        
        // 批量更新数据，减少DOM操作次数
        this.factoryList = processedData;
        this.total = response.total || 0;
      } catch (error) {
        console.error("获取工厂列表失败:", error);
        this.factoryList = [];
        this.total = 0;
      } finally {
        this.loading = false;
      // 结束计时，输出执行时间
      }
    },

    /** 初始化树结构 */
    async initTree() {
      this.loading = true;
      try {
        // 使用已加载的工厂映射数据，避免重复请求
        const factoryIds = Object.keys(this.factoryNameMap);
        const factoryNames = Object.values(this.factoryNameMap);
        
        console.log(`准备构建树结构，使用${factoryIds.length}个工厂节点`);
        
        // 创建工厂节点
        const factoryNodes = [];
        
        // 如果没有工厂数据，尝试重新加载
        if (factoryIds.length === 0) {
          console.log("工厂映射为空，尝试重新加载工厂数据");
          try {
            const factoryRes = await listFactory({ pageSize: 100, pageNum: 1 });
            const factories = factoryRes.rows || [];
            
            // 处理每个工厂
            for (const factory of factories) {
              if (!factory.factory_id) continue;
              
              // 创建工厂节点
              const factoryNode = {
                id: factory.factory_id,
                label: factory.factory_name || '未命名工厂',
                type: 'factory',
                factoryId: factory.factory_id,
                factory_id: factory.factory_id,
                children: []
              };
              
              // 为每个工厂加载车间
              await this.loadWorkshopsForFactory(factoryNode);
              
              factoryNodes.push(factoryNode);
            }
          } catch (error) {
            console.error("重新加载工厂数据失败:", error);
          }
        } else {
          // 使用已有的工厂映射数据
          for (let i = 0; i < factoryIds.length; i++) {
            const factoryId = factoryIds[i];
            const factoryName = factoryNames[i];
            
            const factoryNode = {
              id: factoryId,
              label: factoryName || '未命名工厂',
              type: 'factory',
              factoryId: factoryId,
              factory_id: factoryId,
              children: []
            };
            
            // 为每个工厂加载车间
            await this.loadWorkshopsForFactory(factoryNode);
            
            factoryNodes.push(factoryNode);
          }
        }
        
        // 更新根节点
        this.factoryTree = [
          {
            id: 'root',
            label: '全部',
            type: 'root',
            children: factoryNodes
          }
        ];

        console.log("树初始化完成，共", factoryNodes.length, "个工厂节点");
        return this.factoryTree;
      } catch (error) {
        console.error('初始化树结构失败:', error);
        this.$message.error('加载数据失败，请刷新页面重试');
        // 确保至少有一个根节点
        this.factoryTree = [
          {
            id: 'root',
            label: '全部',
            type: 'root',
            children: []
          }
        ];
        return this.factoryTree;
      } finally {
        this.loading = false;
      }
    },
    
    /** 为工厂加载车间 */
    async loadWorkshopsForFactory(factoryNode, forceReload = false) {
      try {
        // 如果已经加载过且不是强制重新加载，直接返回
        if (factoryNode.loaded && factoryNode.children && factoryNode.children.length > 0 && !forceReload) {
          console.log(`工厂[${factoryNode.label}]的车间已加载，跳过`);
          return factoryNode;
        }
        
        const factoryId = factoryNode.factoryId || factoryNode.factory_id;
        console.log(`加载工厂[${factoryNode.label}]的车间列表`);
        
        // 查询该工厂下的所有车间
        const workshopRes = await listWorkshop({
          basicFactory: {
            factory_id: factoryId
          },
          pageSize: 100, // 使用较大的页面大小确保加载所有车间
          pageNum: 1
        });
        
        const workshops = workshopRes.rows || [];
        console.log(`工厂[${factoryNode.label}]下有${workshops.length}个车间`);
        
        // 保存现有子节点的展开状态
        const expandedChildrenIds = [];
        if (factoryNode.children) {
          factoryNode.children.forEach(child => {
            if (child.expanded) {
              expandedChildrenIds.push(child.id);
            }
          });
        }
        
        // 清空现有子节点
        factoryNode.children = [];
        
        // 处理每个车间
        for (const workshop of workshops) {
          if (!workshop.workshop_id) continue;
          
          // 创建车间节点
          const workshopNode = {
            id: `${factoryId}_${workshop.workshop_id}`,
            label: workshop.workshop_name || '未命名车间',
            type: 'workshop',
            factoryId: factoryId,
            workshopId: workshop.workshop_id,
            workshop_id: workshop.workshop_id,
            children: [],
            loaded: false // 标记为未加载生产线
          };
          
          // 检查是否之前已展开
          if (expandedChildrenIds.includes(workshopNode.id)) {
            workshopNode.expanded = true;
          }
          
          // 为每个车间加载生产线
          await this.loadProductionLinesForWorkshop(workshopNode);
          
          // 添加车间节点到工厂的子节点
          factoryNode.children.push(workshopNode);
        }
        
        // 标记工厂节点为已加载
        factoryNode.loaded = true;
        
        return factoryNode;
      } catch (error) {
        console.error(`加载工厂[${factoryNode.label}]的车间失败:`, error);
        // 确保有一个空的子节点数组
        factoryNode.children = factoryNode.children || [];
        return factoryNode;
      }
    },
    
    /** 为车间加载生产线 */
    async loadProductionLinesForWorkshop(workshopNode, forceReload = false) {
      try {
        // 如果已经加载过且不是强制重新加载，直接返回
        if (workshopNode.loaded && workshopNode.children && workshopNode.children.length > 0 && !forceReload) {
          console.log(`车间[${workshopNode.label}]的生产线已加载，跳过`);
          return workshopNode;
        }
        
        const factoryId = workshopNode.factoryId;
        const workshopId = workshopNode.workshopId || workshopNode.workshop_id;
        console.log(`加载车间[${workshopNode.label}]的生产线列表`);
        
        // 防止重复加载 - 设置状态标记
        const originalLoadingState = this.loading;
        this.loading = true;
        
        try {
          // 查询该车间下的所有生产线 - 增加重试机制
          let lineRes = null;
          let retryCount = 0;
          const maxRetries = 2;
          
          while (!lineRes && retryCount <= maxRetries) {
            try {
              lineRes = await listProductionLine({
                basicFactory: {
                  factory_id: factoryId
                },
                basicWorkshop: {
                  workshop_id: parseInt(workshopId)
                },
                is_delete: 0,
                pageSize: 200, // 使用较大的页面大小确保加载所有生产线
                pageNum: 1
              });
              
              // 检查响应是否有效
              if (!lineRes || !lineRes.rows) {
                console.warn(`第${retryCount + 1}次尝试获取生产线列表返回无效响应`);
                lineRes = null;
                retryCount++;
                if (retryCount <= maxRetries) {
                  // 等待一段时间后重试
                  await new Promise(resolve => setTimeout(resolve, 500));
                }
              }
            } catch (apiError) {
              console.error(`第${retryCount + 1}次获取生产线列表失败:`, apiError);
              retryCount++;
              if (retryCount <= maxRetries) {
                // 等待一段时间后重试
                await new Promise(resolve => setTimeout(resolve, 500));
              }
            }
          }
          
          // 如果所有重试都失败，使用空数组
          const lines = (lineRes && lineRes.rows) ? lineRes.rows : [];
          console.log(`车间[${workshopNode.label}]下有${lines.length}个生产线`);
          
          // 保存现有子节点的展开状态
          const expandedChildrenIds = [];
          if (workshopNode.children) {
            workshopNode.children.forEach(child => {
              if (child.expanded) {
                expandedChildrenIds.push(child.id);
              }
            });
          }
          
          // 清空现有子节点
          workshopNode.children = [];
          
          // 处理每个生产线
          for (const line of lines) {
            const lineId = line.production_line_id || line.line_id;
            if (!lineId) continue;
            
            // 获取正确的生产线名称
            let lineName = '未命名生产线';
            if (line.production_line_name && typeof line.production_line_name === 'string') {
              lineName = line.production_line_name;
            } else if (line.line_name && typeof line.line_name === 'string') {
              lineName = line.line_name;
            }
            
            // 创建生产线节点
            const lineNode = {
              id: `${factoryId}_${workshopId}_${lineId}`,
              label: lineName,
              type: 'line',
              factoryId: factoryId,
              workshopId: workshopId,
              lineId: lineId,
              line_id: lineId,
              production_line_id: lineId, // 添加此字段确保完整性
              isLeaf: true, // 生产线是叶子节点，不再加载子节点
              loaded: true // 标记为已加载（因为是叶子节点）
            };
            
            // 检查是否之前已展开
            if (expandedChildrenIds.includes(lineNode.id)) {
              lineNode.expanded = true;
            }
            
            // 添加生产线节点到车间的子节点
            workshopNode.children.push(lineNode);
          }
          
          // 标记车间节点为已加载
          workshopNode.loaded = true;
          
          return workshopNode;
        } finally {
          // 恢复原始加载状态
          this.loading = originalLoadingState;
        }
      } catch (error) {
        console.error(`加载车间[${workshopNode.label}]的生产线失败:`, error);
        // 确保有一个空的子节点数组
        workshopNode.children = workshopNode.children || [];
        return workshopNode;
      }
    },
    

    
    /** 选择树节点 */
    async handleNodeClick(data) {
      // 防止重复点击同一节点
      if (this.currentNode && this.currentNode.id === data.id) {
        console.log("重复点击同一节点，忽略");
        return;
      }
      
      // 防止在加载中时点击
      if (this.loading) {
        console.log("正在加载数据，忽略点击");
        return;
      }
      
      this.currentNode = data;
      this.currentNodeType = data.type || 'root';
      this.loading = true;
      
      // 重置数据列表
      this.factoryList = [];
      this.productionLineList = [];
      this.workstationList = [];
      
      try {
        // 延迟处理，避免频繁点击
        await this.delay(300);
        
        // 重置查询参数
        this.queryParams = {
          pageNum: 1,
          pageSize: 10
        };
        
        // 根据节点类型加载不同的数据
        if (data.type === 'root' || !data.type) {
          // 点击"全部"节点，显示所有工厂
          // 设置当前节点类型为工厂，以便显示正确的表格列
          this.currentNodeType = 'factory';
          console.log("点击全部节点，加载所有工厂");
          await this.getList();
        } else if (data.type === 'factory') {
          // 加载工厂下的所有车间
          const factoryId = data.id || data.factoryId || data.factory_id;
          
          this.queryParams = {
            ...this.queryParams,
            factoryId: factoryId,
            factory_id: factoryId,
            basicFactory: {
              factory_id: factoryId
            }
          };
          console.log(`点击工厂节点[${data.label}]，加载其下车间`);
          // 设置当前节点类型为车间，以便显示正确的表格列
          this.currentNodeType = 'workshop';
          await this.getWorkshopList();
          
          // 如果节点未加载子节点，加载车间子节点
          if (!data.loaded) {
            await this.loadWorkshopsForFactory(data);
            data.loaded = true;
          }
        } else if (data.type === 'workshop') {
          // 加载车间下的所有生产线
          const workshopId = data.id ? data.id.split('_')[1] : data.workshopId || data.workshop_id;
          const factoryId = data.factoryId || data.factory_id;
          
          this.queryParams = {
            ...this.queryParams,
            factoryId: factoryId,
            factory_id: factoryId,
            basicFactory: {
              factory_id: factoryId
            },
            workshopId: parseInt(workshopId),
            workshop_id: parseInt(workshopId),
            basicWorkshop: {
              workshop_id: parseInt(workshopId)
            }
          };
          console.log(`点击车间节点[${data.label}]，加载其下生产线`);
          // 设置当前节点类型为生产线，以便显示正确的表格列
          this.currentNodeType = 'line';
          await this.getLineList();
          
          // 如果节点未加载子节点，加载生产线子节点
          if (!data.loaded) {
            await this.loadProductionLinesForWorkshop(data);
            data.loaded = true;
          }
        } else if (data.type === 'line') {
          // 加载生产线下的所有工位，此处需添加工位查询API
          const lineId = data.id ? data.id.split('_')[2] : data.lineId || data.line_id;
          const workshopId = data.workshopId || data.workshop_id;
          const factoryId = data.factoryId || data.factory_id;
          
          this.queryParams = {
            ...this.queryParams,
            factoryId: factoryId,
            factory_id: factoryId,
            basicFactory: {
              factory_id: factoryId
            },
            workshopId: workshopId,
            workshop_id: workshopId,
            basicWorkshop: {
              workshop_id: workshopId
            },
            lineId: parseInt(lineId),
            line_id: parseInt(lineId),
            basicLine: {
              line_id: parseInt(lineId)
            }
          };
          console.log(`点击生产线节点[${data.label}]，加载其下工位`);
          // 设置当前节点类型为工位，以便显示正确的表格列
          this.currentNodeType = 'workstation';
          await this.getWorkstationList();
        }
      } catch(error) {
        console.error("加载节点数据失败:", error);
      } finally {
        this.loading = false;
      }
    },
    
    /** 加载车间列表 */
    async getWorkshopList() {
      try {
        // 获取查询参数中的工厂ID
        const factoryId = this.queryParams.factoryId || this.queryParams.factory_id;
        
        // 根据SQL参数格式构建查询条件
        const res = await listWorkshop({
          basicFactory: {
            factory_id: factoryId
          },
          workshop_name: this.queryParams.workshop_name,
          pageNum: this.queryParams.pageNum || 1,
          pageSize: this.queryParams.pageSize || 10
        });
        
        console.log(`加载工厂[${factoryId}]的车间列表结果:`, res);
        
        // 处理返回数据，确保字段名一致
        this.factoryList = (res.rows || []).map(workshop => {
          // 详细日志，查看每个车间的字段
          console.log('车间数据详情:', JSON.stringify(workshop));
          
          // 确定正确的工厂名称
          let factoryName = '';
          if (workshop.factory_name) {
            factoryName = workshop.factory_name;
          } else if (workshop.basicFactory && workshop.basicFactory.factory_name) {
            factoryName = workshop.basicFactory.factory_name;
          }
          
          // 确定正确的备注
          let remarks = '';
          if (workshop.remarks) {
            remarks = workshop.remarks;
          } else if (workshop.remark) {
            remarks = workshop.remark;
          }
          
          // 确定正确的创建人
          let createBy = '';
          if (workshop.create_by) {
            createBy = workshop.create_by;
          } else if (workshop.createBy) {
            createBy = workshop.createBy;
          } else if (workshop.created_by) {
            createBy = workshop.created_by;
          }
          
          return {
            // ID字段
            workshopId: workshop.workshop_id || workshop.workshopId,
            workshop_id: parseInt(workshop.workshop_id || workshop.workshopId || 0),
            // 基本信息
            workshop_name: workshop.workshop_name || '未命名',
            workshop_code: workshop.workshop_code || '-',
            // 其他信息
            factory_id: workshop.factory_id || factoryId,
            factory_name: factoryName || '-',
            // 系统字段
            remarks: remarks || '',
            create_by: createBy || '-',
            create_time: workshop.create_time || workshop.createTime || '',
            update_time: workshop.update_time || workshop.updateTime || '',
          };
        });
        
        this.total = res.total || 0;
      } catch(error) {
        console.error("获取车间列表失败:", error);
        this.factoryList = [];
        this.total = 0;
      }
    },
    
    /** 加载生产线列表 */
    async getLineList() {
      try {
        // 避免重复请求
        if (this.isLoading) {
          console.log("已有请求正在进行，跳过此次请求");
          return;
        }
        
        // 清空现有生产线数据，避免删除后还显示旧数据
        this.productionLineList = [];
        
        // 设置加载状态
        this.loading = true;
        this.isLoading = true; // 额外的标志，避免重复请求
        
        // 获取查询参数中的工厂ID和车间ID
        const factoryId = this.queryParams.factoryId || this.queryParams.factory_id;
        const workshopId = this.queryParams.workshopId || this.queryParams.workshop_id;
        
        console.log("加载生产线列表，车间ID:", workshopId, "工厂ID:", factoryId);
        
        // 根据SQL参数格式构建查询条件 - 对应SQL语句中的条件
        const query = {
          basicFactory: {
            factory_id: factoryId
          },
          basicWorkshop: {
            workshop_id: parseInt(workshopId)
          },
          // 确保is_delete=0的条件
          is_delete: 0,
          pageNum: this.queryParams.pageNum || 1,
          pageSize: this.queryParams.pageSize || 10
        };
        
        // 如果有关键词，添加到查询条件
        if (this.queryParams.keyword) {
          query.keyword = this.queryParams.keyword;
        }
        
        // 添加重试机制
        let res = null;
        let retryCount = 0;
        const maxRetries = 2;
        
        while (!res && retryCount <= maxRetries) {
          try {
            res = await listProductionLine(query);
            
            // 检查响应是否有效
            if (!res) {
              console.warn(`第${retryCount + 1}次尝试获取生产线列表返回无效响应`);
              res = null;
              retryCount++;
              if (retryCount <= maxRetries) {
                // 等待一段时间后重试
                await new Promise(resolve => setTimeout(resolve, 300));
              }
            }
          } catch (apiError) {
            console.error(`第${retryCount + 1}次获取生产线列表失败:`, apiError);
            retryCount++;
            if (retryCount <= maxRetries) {
              // 等待一段时间后重试
              await new Promise(resolve => setTimeout(resolve, 300));
            } else {
              throw apiError; // 最后一次尝试失败时抛出错误
            }
          }
        }
        
        console.log(`加载车间[${workshopId}]的生产线列表结果:`, res);
        
        if (!res) {
          console.error("获取生产线列表返回为空");
          this.productionLineList = [];
          this.total = 0;
          return;
        }
        
        // 处理返回数据，确保字段名一致，对应SQL查询结果的字段
        this.productionLineList = (res.rows || []).map(line => {
          // SQL查询中连接了多个表，可能有多种命名方式
          // 从basic_productionline表获取生产线信息
          const lineCode = line.production_line_code || line.line_code || '-';
          const lineName = line.production_line_name || line.line_name || '-';
          const lineRemarks = line.remarks || line.remark || '-';
          
          // 从basic_workshop表获取车间信息
          const workshopName = line.workshop_name || 
                              (line.basicWorkshop ? line.basicWorkshop.workshop_name : '-');
          
          // 从basic_factory表获取工厂信息 - 直接使用factory_name字段
          let factoryName = '-';
          
          // 优先使用直接的factory_name字段
          if (line.factory_name && typeof line.factory_name === 'string') {
            factoryName = line.factory_name;
          } 
          // 如果在嵌套对象中
          else if (line.basicFactory && line.basicFactory.factory_name) {
            factoryName = line.basicFactory.factory_name;
          }
          
          // 创建人信息
          const createBy = line.create_by || line.createBy || line.created_by || 'admin';
          
          // 创建时间
          const createTime = line.create_time || line.createTime || line.created_time || '';
          
          // 确保生产线ID是整数类型
          const lineId = parseInt(line.production_line_id || line.line_id || 0);
          
          return {
            // ID字段 - 确保同时包含不同命名方式的ID字段
            lineId: lineId,
            line_id: lineId,
            production_line_id: lineId,
            // 基本信息 - 对应图片中的列
            create_time: createTime,
            line_code: lineCode,
            line_name: lineName,
            workshop_name: workshopName,
            factory_name: factoryName, // 确保使用正确的工厂名称
            remarks: lineRemarks,
            create_by: createBy,
            // 其他信息
            workshop_id: parseInt(line.workshop_id || workshopId),
            factory_id: line.factory_id || factoryId,
            update_by: line.update_by || line.updateBy || '',
            update_time: line.update_time || line.updateTime || '',
          };
        });
        
        this.total = res.total || 0;
      } catch(error) {
        console.error("获取生产线列表失败:", error);
        this.$message.error("获取生产线列表失败: " + (error.message || "未知错误"));
        this.productionLineList = [];
        this.total = 0;
      } finally {
        this.loading = false;
        this.isLoading = false; // 重置加载标志
        
        // 延迟一点时间后清除可能的错误状态
        setTimeout(() => {
          this.$nextTick(() => {
            // 强制刷新视图
            this.$forceUpdate();
          });
        }, 100);
      }
    },

    /** 加载工位列表 */
    async getWorkstationList() {
      try {
        // 获取查询参数中的工厂ID、车间ID和生产线ID
        const factoryId = this.queryParams.factoryId || this.queryParams.factory_id;
        const workshopId = this.queryParams.workshopId || this.queryParams.workshop_id;
        const lineId = this.queryParams.lineId || this.queryParams.line_id;
        
        console.log("加载工位列表，生产线ID:", lineId, "车间ID:", workshopId, "工厂ID:", factoryId);
        
        // 调用工位列表API
        const res = await listWorkstation({
          basicFactory: {
            factory_id: factoryId
          },
          basicWorkshop: {
            workshop_id: parseInt(workshopId)
          },
          basicProductionline: {  // Note: lowercase 'l' in Productionline to match backend SQL
            production_line_id: parseInt(lineId)
          },
          station_name: this.queryParams.station_name,
          pageNum: this.queryParams.pageNum || 1,
          pageSize: this.queryParams.pageSize || 10
        });
        
        console.log(`加载生产线[${lineId}]的工位列表结果:`, res);
        
        // 处理返回数据，确保字段名一致
        this.workstationList = (res.rows || []).map(station => {
          // 详细日志，查看每个工位的字段
          console.log("工位数据详情:", JSON.stringify(station));
          
          // 直接查看原始的workshop_name和factory_name字段
          console.log('原始workshop_name:', station.workshop_name);
          console.log('原始factory_name:', station.factory_name);
          
          // 确定正确的工厂名称 - 从JSON数据中提取
          let factoryName = '-';
          if (station.factory_name && typeof station.factory_name === 'string') {
            factoryName = station.factory_name;
          } else if (station.basicFactory && station.basicFactory.factory_name) {
            factoryName = station.basicFactory.factory_name;
          }
          
          // 确定正确的车间名称 - 从JSON数据中提取
          let workshopName = '-';
          if (station.workshop_name && typeof station.workshop_name === 'string') {
            workshopName = station.workshop_name;
          } else if (station.basicWorkshop && station.basicWorkshop.workshop_name) {
            workshopName = station.basicWorkshop.workshop_name;
          }
          
          // 确定正确的生产线名称
          let lineName = '-';
          if (station.production_line_name) {
            lineName = station.production_line_name;
          } else if (station.line_name) {
            lineName = station.line_name;
          } else if (station.basicProductionline && station.basicProductionline.production_line_name) {
            lineName = station.basicProductionline.production_line_name;
          }
          
          // 确定正确的备注
          let remarks = '';
          if (station.remarks) {
            remarks = station.remarks;
          } else if (station.remark) {
            remarks = station.remark;
          }
          
          // 确定正确的创建人
          let createBy = '';
          if (station.create_by) {
            createBy = station.create_by;
          } else if (station.createBy) {
            createBy = station.createBy;
          } else if (station.created_by) {
            createBy = station.created_by;
          }
          
          // 打印最终使用的值
          console.log('最终使用的工厂名称:', factoryName);
          console.log('最终使用的车间名称:', workshopName);
          
          return {
            // ID字段
            stationId: station.station_id || station.stationId,
            station_id: parseInt(station.station_id || station.stationId || 0),
            // 基本信息
            station_name: station.station_name || '未命名',
            station_code: station.station_code || '-',
            // 其他信息
            line_id: parseInt(station.production_line_id || lineId || 0),
            line_name: lineName || '-',
            production_line_name: lineName || '-', // 添加额外的字段映射
            workshop_id: parseInt(station.workshop_id || workshopId || 0),
            workshop_name: workshopName, // 使用从JSON中提取的车间名称
            factory_id: station.factory_id || factoryId,
            factory_name: factoryName, // 使用从JSON中提取的工厂名称
            // 系统字段
            remarks: remarks || '',
            create_by: createBy || '-',
            create_time: station.create_time || station.createTime || '',
            update_time: station.update_time || station.updateTime || '',
          };
        });
        
        this.total = res.total || 0;
      } catch(error) {
        console.error("获取工位列表失败:", error);
        this.workstationList = [];
        this.total = 0;
      }
    },

    /** 处理分页事件 */
    handlePagination() {
      // 根据当前节点类型调用不同的列表加载方法
      if (this.currentNodeType === 'factory') {
        this.getList();
      } else if (this.currentNodeType === 'workshop') {
        this.getWorkshopList();
      } else if (this.currentNodeType === 'line') {
        this.getLineList();
      } else if (this.currentNodeType === 'workstation') {
        this.getWorkstationList();
      }
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.handlePagination();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 表单重置 */
    reset() {
      // 根据表单类型重置不同的表单字段
      if (this.formType === 'factory' || !this.formType) {
        this.form = {
          factory_id: null,
          factory_code: "", // 使用空字符串而不是null，确保Vue正确绑定
          factory_name: null,
          factory_address: null,
          remarks: null,
        };
              // 注释掉这里的自动获取，避免重复调用
      // 由handleAdd方法单独处理自动获取编号
      /*
      if ((!this.form.id || !this.form.factory_id) && 
          (this.title === "新增工厂" || this.formType === 'factory')) {
        console.log("准备自动获取工厂编号");
        setTimeout(() => {
          this.handleGetAutoNumber();
        }, 100);
      }
      */
      } else if (this.formType === 'workshop') {
        const factoryId = this.currentNode ? (this.currentNode.factoryId || this.currentNode.factory_id) : null;
        const factoryName = factoryId ? (this.factoryNameMap[factoryId] || this.currentNode.label || '未知工厂') : '';
        
        this.form = {
          factory_id: factoryId,
          factory_name: factoryName, // 添加工厂名称
          workshop_code: "", // 使用空字符串而不是null，确保Vue正确绑定
          workshop_name: null,
          remarks: null,
        };
      } else if (this.formType === 'line') {
        this.form = {
          factory_id: this.currentNode ? (this.currentNode.factoryId || this.currentNode.factory_id) : null,
          workshop_id: this.currentNode ? (this.currentNode.workshopId || this.currentNode.workshop_id) : null,
          line_code: null,
          line_name: null,
          remarks: null,
        };
      } else if (this.formType === 'workstation') {
        const factoryId = this.currentNode ? (this.currentNode.factoryId || this.currentNode.factory_id) : null;
        const workshopId = this.currentNode ? (this.currentNode.workshopId || this.currentNode.workshop_id) : null;
        const lineId = this.currentNode ? (this.currentNode.lineId || this.currentNode.line_id) : null;
        
        // 获取名称
        const factoryName = factoryId ? (this.factoryNameMap[factoryId] || '未知工厂') : '';
        const workshopName = workshopId ? (this.workshopNameMap[workshopId] || '未知车间') : '';
        const lineName = this.currentNode ? this.currentNode.label : '';
        
        this.form = {
          factory_id: factoryId,
          factory_name: factoryName,
          workshop_id: workshopId,
          workshop_name: workshopName,
          line_id: lineId,
          production_line_name: lineName, // 使用production_line_name字段与后端匹配
          line_name: lineName, // 兼容可能的字段名
          station_code: null,
          station_name: null,
          remarks: null,
        };
      }
      
      this.resetForm("form");
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      if (this.currentNodeType === 'line') {
        this.ids = selection.map(item => item.line_id);
      } else if (this.currentNodeType === 'workshop') {
        this.ids = selection.map(item => item.workshop_id);
      } else if (this.currentNodeType === 'workstation') {
        this.ids = selection.map(item => item.station_id);
      } else {
        this.ids = selection.map(item => item.factory_id);
      }
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      
      // 根据当前选中的节点类型，显示不同的表单
      if (this.currentNodeType === 'factory' || this.currentNodeType === 'root') {
        // 在根节点或工厂列表页面点击新增，显示工厂表单
        this.formType = 'factory';
        this.title = "新增工厂";
        
        // 不再自动获取编号，由用户点击按钮触发
        this.form.factory_code = ""; // 清空编号，等待用户点击按钮获取
      } else if (this.currentNodeType === 'workshop') {
        // 在工厂节点点击新增，显示车间表单
        this.formType = 'workshop';
        this.title = "新增车间";
        // 预设所属工厂
        const factoryId = this.currentNode.factoryId || this.currentNode.factory_id;
        const factoryName = this.factoryNameMap[factoryId] || this.currentNode.label || '未知工厂';
        
        this.form = {
          factory_id: factoryId,
          factory_name: factoryName, // 添加工厂名称
          workshop_code: "",
          workshop_name: "",
          remarks: ""
        };
      } else if (this.currentNodeType === 'line') {
        // 在车间节点点击新增，显示生产线表单
        this.formType = 'line';
        this.title = "新增生产线";
        // 预设所属工厂和车间
        this.form.factory_id = this.currentNode.factoryId || this.currentNode.factory_id;
        this.form.workshop_id = this.currentNode.workshopId || this.currentNode.workshop_id;
      } else if (this.currentNodeType === 'workstation') {
        // 在生产线节点点击新增，显示工位表单
        this.formType = 'workstation';
        this.title = "新增工位";
        // 预设所属工厂、车间和生产线
        const factoryId = this.currentNode.factoryId || this.currentNode.factory_id;
        const workshopId = this.currentNode.workshopId || this.currentNode.workshop_id;
        const lineId = this.currentNode.lineId || this.currentNode.line_id;
        
        // 获取名称
        const factoryName = this.factoryNameMap[factoryId] || '未知工厂';
        const workshopName = this.workshopNameMap[workshopId] || '未知车间';
        const lineName = this.currentNode.label || '未知生产线';
        
        this.form = {
          factory_id: factoryId,
          factory_name: factoryName,
          workshop_id: workshopId,
          workshop_name: workshopName,
          line_id: lineId,
          production_line_name: lineName, // 使用production_line_name字段与后端匹配
          line_name: lineName, // 兼容可能的字段名
          station_code: "",
          station_name: "",
          remarks: ""
        };
      }
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      
      if (this.currentNodeType === 'factory') {
        this.formType = 'factory';
        
        // 直接使用当前行数据，避免额外的API调用
        try {
          console.log("准备修改工厂，使用当前行数据:", row);
          
          // 深拷贝行数据，避免直接修改表格数据
          this.form = JSON.parse(JSON.stringify(row));
          
          // 确保必要的字段都存在
          if (!this.form.factory_code && this.form.factory_id) {
            this.form.factory_code = this.form.factory_id;
          }
          
          // 打开对话框
          this.open = true;
          this.title = "修改工厂";
          
          console.log("表单数据设置完成:", this.form);
        } catch (error) {
          console.error("处理工厂数据出错:", error);
          this.$message.error("准备修改工厂失败，请重试");
        }
      } else if (this.currentNodeType === 'workshop') {
        this.formType = 'workshop';
        const workshopId = row.workshop_id || this.ids[0];
        getWorkshop(workshopId).then(response => {
          this.form = response.data;
          
          // 从factoryNameMap中获取工厂名称
          const factoryId = this.form.factory_id;
          if (factoryId && this.factoryNameMap[factoryId]) {
            // 设置当前节点以便下拉框正确显示工厂名称
            this.currentNode = {
              factoryId: factoryId,
              label: this.factoryNameMap[factoryId] || '未知工厂'
            };
          }
          
          this.open = true;
          this.title = "修改车间";
        });
      } else if (this.currentNodeType === 'line') {
        this.formType = 'line';
        const lineId = row.line_id || this.ids[0];
        getProductionLine(lineId).then(response => {
          console.log("获取到生产线详情数据:", response.data);
          
          // 从后端获取的数据
          const lineData = response.data;
          
          // 构造表单数据，确保字段名称映射正确
          this.form = {
            // 保留ID字段 - 同时保存为line_id和production_line_id以确保后端能够识别
            id: lineId,
            line_id: lineId,
            production_line_id: lineId, // 添加此字段确保后端可以识别
            
            // 关联信息 - 工厂和车间ID
            factory_id: lineData.factory_id,
            workshop_id: lineData.workshop_id,
            
            // 基本信息 - 映射生产线编号和名称字段
            line_code: lineData.production_line_code || lineData.line_code || '',
            line_name: lineData.production_line_name || lineData.line_name || '',
            production_line_code: lineData.production_line_code || lineData.line_code || '', // 添加后端字段名
            production_line_name: lineData.production_line_name || lineData.line_name || '', // 添加后端字段名
            
            // 其他信息
            remarks: lineData.remarks || ''
          };
          
          // 更新currentNode以确保下拉菜单正确显示
          if (lineData.factory_id && lineData.workshop_id) {
            this.currentNode = {
              factoryId: lineData.factory_id,
              workshopId: lineData.workshop_id,
              label: lineData.workshop_name || this.workshopNameMap[lineData.workshop_id] || '未知车间'
            };
          }
          
          this.open = true;
          this.title = "修改生产线";
        }).catch(error => {
          console.error("获取生产线详情失败:", error);
          this.$message.error("获取生产线详情失败，请重试");
        });
      } else if (this.currentNodeType === 'workstation') {
        this.formType = 'workstation';
        const stationId = row.station_id || this.ids[0];
        getWorkstation(stationId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改工位";
        });
      }
    },

    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          try {
            // 根据表单类型调用不同的API
            if (this.formType === 'factory') {
              // 工厂表单提交
              console.log("提交工厂表单:", this.form);
              
              // 确保factory_id字段正确
              if (this.form.factory_id || this.form.id) {
                // 更新工厂
                const updateData = { ...this.form };
                // 确保ID字段正确
                if (!updateData.factory_id && updateData.id) {
                  updateData.factory_id = updateData.id;
                }
                
                // 确保编号字段存在
                if (!updateData.factory_code && updateData.factory_id) {
                  updateData.factory_code = updateData.factory_id;
                }
                
                console.log("更新工厂数据:", updateData);
                try {
                  await updateFactory(updateData);
                  this.$modal.msgSuccess("修改工厂成功");
                  
                  // 修改工厂后更新工厂映射和树节点
                  const factoryId = updateData.factory_id || updateData.id;
                  const factoryName = updateData.factory_name || '未命名工厂';
                  
                  // 更新工厂名称映射
                  this.factoryNameMap[factoryId] = factoryName;
                  
                  // 保存当前树的展开状态和选中节点
                  let currentSelectedKey = null;
                  const expandedKeys = [];
                  
                  if (this.$refs.tree) {
                    // 获取当前选中节点
                    currentSelectedKey = this.$refs.tree.getCurrentKey();
                    
                    // 收集所有已展开节点
                    const store = this.$refs.tree.store;
                    if (store && store.nodesMap) {
                      Object.keys(store.nodesMap).forEach(key => {
                        if (store.nodesMap[key].expanded) {
                          expandedKeys.push(key);
                        }
                      });
                    }
                    console.log("保存展开节点状态:", expandedKeys);
                  }
                  
                  // 直接重新加载树结构 - 这是确保更新最可靠的方法
                  console.log("重新加载树结构...");
                  await this.loadFactoryNameMap();
                  await this.initTreeWithLazyLoading();
                  
                  // 在树重新加载后恢复展开和选中状态
                  this.$nextTick(() => {
                    if (this.$refs.tree) {
                      console.log("恢复树节点状态...");
                      
                      // 首先确保根节点展开
                      const root = this.$refs.tree.store.nodesMap.root;
                      if (root) root.expanded = true;
                      
                      // 恢复之前的展开状态
                      expandedKeys.forEach(key => {
                        const node = this.$refs.tree.store.nodesMap[key];
                        if (node) {
                          node.expanded = true;
                        }
                      });
                      
                      // 恢复选中状态
                      if (currentSelectedKey) {
                        this.$refs.tree.setCurrentKey(currentSelectedKey);
                      }
                    }
                  });
                } catch (error) {
                  console.error("更新工厂失败:", error);
                  this.$modal.msgError("修改工厂失败: " + (error.message || "未知错误"));
                  return; // 失败时提前返回，不关闭对话框
                }
              } else {
                // 新增工厂
                // 如果是新增模式且有工厂编号，在提交前获取真正的编号
                if (this.form.factory_code) {
                  try {
                    const response = await getAutoNumbersConsume(22);
                    if (typeof response === 'string') {
                      this.form.factory_code = response;
                    } else if (response && response.msg) {
                      this.form.factory_code = response.msg;
                    } else if (response && response.data) {
                      this.form.factory_code = response.data;
                    }
                  } catch (error) {
                    this.$modal.msgError('获取最终工厂编号失败');
                    return;
                  }
                }
                
                console.log("新增工厂数据:", this.form);
                const response = await addFactory(this.form);
                this.$modal.msgSuccess("新增工厂成功");
                
                // 在成功新增工厂后，确保更新工厂名称映射和树结构
                await this.loadFactoryNameMap();
                await this.initTreeWithLazyLoading();
              }
              
              // 更新表格数据
              await this.getList();
            } 
            else if (this.formType === 'workshop') {
              // 车间表单提交
              if (this.form.id || this.form.workshop_id) {
                // 更新车间 - 确保工厂名称和ID都传递给后端
                const factoryId = this.form.factory_id;
                const factoryName = this.factoryNameMap[factoryId] || '未知工厂';
                
                // 构建包含工厂名称的提交数据
                const workshopData = {
                  ...this.form,
                  factory_name: factoryName  // 确保工厂名称字段存在
                };
                
                console.log("更新车间数据:", workshopData);
                await updateWorkshop(workshopData);
                this.$modal.msgSuccess("修改车间成功");
                
                // 保存当前树的展开状态和选中节点
                let currentSelectedKey = null;
                const expandedKeys = [];
                
                if (this.$refs.tree) {
                  // 获取当前选中节点
                  currentSelectedKey = this.$refs.tree.getCurrentKey();
                  
                  // 收集所有已展开节点
                  const store = this.$refs.tree.store;
                  if (store && store.nodesMap) {
                    Object.keys(store.nodesMap).forEach(key => {
                      if (store.nodesMap[key].expanded) {
                        expandedKeys.push(key);
                      }
                    });
                  }
                  console.log("保存展开节点状态:", expandedKeys);
                }

                // 更新车间名称映射
                await this.loadWorkshopNameMap();
                
                // 找到对应的工厂节点并更新车间信息
                if (this.$refs.tree && this.$refs.tree.store) {
                  const store = this.$refs.tree.store;
                  const factoryNode = store.nodesMap[factoryId];
                  
                  if (factoryNode && factoryNode.data) {
                    console.log("找到工厂节点:", factoryNode.data.label);
                    
                    // 获取当前编辑的车间ID和更新的名称
                    const workshopId = this.form.workshop_id || this.form.id;
                    const updatedWorkshopName = this.form.workshop_name;
                    console.log("正在更新车间节点, ID:", workshopId, "新名称:", updatedWorkshopName);
                    
                    // 尝试直接更新树节点
                    let workshopNodeUpdated = false;
                    
                    // 查找并更新树视图中的节点
                    if (factoryNode.childNodes && factoryNode.childNodes.length > 0) {
                      for (const childNode of factoryNode.childNodes) {
                        // 查找匹配的车间节点
                        if (childNode.data && 
                            (childNode.data.workshopId == workshopId || childNode.data.workshop_id == workshopId)) {
                          
                          console.log("在树视图中找到匹配的车间节点:", childNode.data.label);
                          
                          // 使用Vue的响应式方法更新节点标签
                          this.$set(childNode.data, 'label', updatedWorkshopName);
                          workshopNodeUpdated = true;
                          break;
                        }
                      }
                    }
                    
                    // 同时更新原始数据中的节点
                    if (factoryNode.data.children && factoryNode.data.children.length > 0) {
                      for (let i = 0; i < factoryNode.data.children.length; i++) {
                        const child = factoryNode.data.children[i];
                        if (child.workshopId == workshopId || child.workshop_id == workshopId) {
                          console.log("在原始数据中找到匹配的车间节点:", child.label);
                          
                          // 更新原始数据中的节点标签
                          this.$set(factoryNode.data.children[i], 'label', updatedWorkshopName);
                          
                          // 确保Vue检测到数据变化
                          const updatedChildren = [...factoryNode.data.children];
                          this.$set(factoryNode.data, 'children', updatedChildren);
                          workshopNodeUpdated = true;
                          break;
                        }
                      }
                    }
                    
                    // 如果无法直接更新节点，重新加载工厂的车间
                    if (!workshopNodeUpdated) {
                      console.log("未找到匹配的车间节点，重新加载工厂的所有车间");
                      await this.loadWorkshopsForFactory(factoryNode.data, true);
                    }
                    
                    // 更新树视图
                    this.$nextTick(() => {
                      // 确保根节点展开
                      const root = store.nodesMap.root;
                      if (root) root.expanded = true;
                      
                      // 确保工厂节点展开
                      if (factoryNode) factoryNode.expanded = true;
                      
                      // 恢复之前的展开状态
                      expandedKeys.forEach(key => {
                        const node = store.nodesMap[key];
                        if (node) node.expanded = true;
                      });
                      
                      // 恢复选中状态
                      if (currentSelectedKey) {
                        this.$refs.tree.setCurrentKey(currentSelectedKey);
                      }
                      
                      // 强制更新树视图
                      this.$refs.tree.$forceUpdate();
                      
                      // 再次更新，确保视图更新
                      setTimeout(() => {
                        this.$forceUpdate();
                        if (this.$refs.tree) this.$refs.tree.$forceUpdate();
                      }, 200);
                    });
                  } else {
                    console.warn("未找到工厂节点，重新加载整个树结构");
                    await this.initTreeWithLazyLoading();
                    
                    // 恢复树状态
                    this.$nextTick(() => {
                      // 恢复展开状态
                      expandedKeys.forEach(key => {
                        const node = this.$refs.tree.store.nodesMap[key];
                        if (node) node.expanded = true;
                      });
                      
                      // 恢复选中状态
                      if (currentSelectedKey) {
                        this.$refs.tree.setCurrentKey(currentSelectedKey);
                      }
                    });
                  }
                }
              } else {
                // 新增车间 - 确保工厂名称和ID都传递给后端
                // 从工厂映射中获取工厂名称
                const factoryId = this.form.factory_id;
                const factoryName = this.factoryNameMap[factoryId] || this.currentNode.label || '未知工厂';
                
                // 如果是新增模式且有车间编号，在提交前获取真正的编号
                if (this.form.workshop_code) {
                  try {
                    const response = await getAutoNumbersConsume(23);
                    if (typeof response === 'string') {
                      this.form.workshop_code = response;
                    } else if (response && response.msg) {
                      this.form.workshop_code = response.msg;
                    } else if (response && response.data) {
                      this.form.workshop_code = response.data;
                    }
                  } catch (error) {
                    this.$modal.msgError('获取最终车间编号失败');
                    return;
                  }
                }
                
                // 构建包含工厂名称的提交数据
                const workshopData = {
                  ...this.form,
                  factory_name: factoryName,  // 确保工厂名称字段存在
                  factory_id: factoryId       // 确保工厂ID字段存在
                };
                
                console.log("提交车间数据:", workshopData);
                const response = await addWorkshop(workshopData);
                this.$modal.msgSuccess("新增车间成功");
                
                // 保存当前树的展开状态和选中节点
                let currentSelectedKey = null;
                const expandedKeys = [];
                
                if (this.$refs.tree) {
                  // 获取当前选中节点
                  currentSelectedKey = this.$refs.tree.getCurrentKey();
                  
                  // 收集所有已展开节点
                  const store = this.$refs.tree.store;
                  if (store && store.nodesMap) {
                    Object.keys(store.nodesMap).forEach(key => {
                      if (store.nodesMap[key].expanded) {
                        expandedKeys.push(key);
                      }
                    });
                  }
                  console.log("保存展开节点状态:", expandedKeys);
                }
                
                // 更新数据缓存
                await this.loadWorkshopNameMap();
                
                // 完全重新加载树结构 - 这是确保更新最可靠的方法
                console.log("重新加载整个树结构...");
                await this.initTreeWithLazyLoading();
                
                // 在树重新加载后恢复展开状态
                this.$nextTick(() => {
                  if (this.$refs.tree) {
                    console.log("恢复树节点状态...");
                    
                    // 首先确保根节点展开
                    const root = this.$refs.tree.store.nodesMap.root;
                    if (root) root.expanded = true;
                    
                    // 特别确保工厂节点展开，这样才能看到新增的车间
                    const factoryNode = this.$refs.tree.store.nodesMap[factoryId];
                    if (factoryNode) {
                      factoryNode.expanded = true;
                      console.log("已展开工厂节点:", factoryId);
                    }
                    
                    // 恢复之前的展开状态
                    expandedKeys.forEach(key => {
                      const node = this.$refs.tree.store.nodesMap[key];
                      if (node) {
                        node.expanded = true;
                      }
                    });
                    
                    // 恢复选中状态，优先选择当前工厂
                    if (factoryId) {
                      this.$refs.tree.setCurrentKey(factoryId);
                    } else if (currentSelectedKey) {
                      this.$refs.tree.setCurrentKey(currentSelectedKey);
                    }
                    
                    // 确保视图更新
                    setTimeout(() => {
                      this.$refs.tree.$forceUpdate();
                    }, 100);
                  }
                });
              }
              // 刷新车间列表
              await this.getWorkshopList();
            } 
            else if (this.formType === 'line') {
              // 生产线表单提交
              if (this.form.id) {
                // 更新生产线
                try {
                  // 确保包含production_line_id字段以便后端识别要更新的记录
                  const updateData = { 
                    ...this.form,
                    production_line_id: this.form.id || this.form.line_id,
                    // 确保字段名称符合后端需求
                    production_line_code: this.form.line_code,
                    production_line_name: this.form.line_name,
                    // 确保包含工厂和车间信息
                    factory_id: this.form.factory_id,
                    workshop_id: this.form.workshop_id
                  };
                  
                  console.log("更新生产线数据:", updateData);
                  await updateProductionLine(updateData);
                  this.$modal.msgSuccess("修改生产线成功");
                  
                  // 保存当前树的展开状态和选中节点
                  let currentSelectedKey = null;
                  const expandedKeys = [];
                  
                  if (this.$refs.tree) {
                    // 获取当前选中节点
                    currentSelectedKey = this.$refs.tree.getCurrentKey();
                    
                    // 收集所有已展开节点
                    const store = this.$refs.tree.store;
                    if (store && store.nodesMap) {
                      Object.keys(store.nodesMap).forEach(key => {
                        if (store.nodesMap[key].expanded) {
                          expandedKeys.push(key);
                        }
                      });
                    }
                    console.log("保存展开节点状态:", expandedKeys);
                  }
                  
                  // 关闭对话框并清空表单，先于数据加载
                  this.open = false;
                  this.reset();
                  
                  // 延迟一段时间再加载数据，避免"数据正在处理"错误
                  await new Promise(resolve => setTimeout(resolve, 300));
                  
                  // 刷新生产线列表
                  await this.getLineList();
                  
                  // 获取工厂ID和车间ID
                  const factoryId = this.currentNode ? (this.currentNode.factoryId || this.queryParams.factoryId) : null;
                  const workshopId = this.currentNode ? (this.currentNode.workshopId || this.queryParams.workshopId) : null;
                  
                  if (factoryId && workshopId) {
                    // 更新树结构 - 使用更可靠的完全重新加载方式
                    try {
                      console.log("准备完全刷新树结构以反映生产线更新");
                      
                      // 完全重新加载工厂和车间映射
                      await this.loadFactoryNameMap();
                      await this.loadWorkshopNameMap();
                      
                      // 查找车间节点
                      if (this.$refs.tree && this.$refs.tree.store) {
                        const workshopNodeId = `${factoryId}_${workshopId}`;
                        const store = this.$refs.tree.store;
                        const workshopNode = store.nodesMap[workshopNodeId];
                        
                        if (workshopNode && workshopNode.data) {
                          console.log("找到车间节点:", workshopNode.data.label, "，重新加载生产线");
                          
                          // 先完全清空该车间的所有生产线
                          if (workshopNode.data.children) {
                            workshopNode.data.children = [];
                          }
                          
                          // 设置为未加载状态，确保重新加载
                          workshopNode.data.loaded = false;
                          workshopNode.childNodes = [];
                          
                          // 强制重新加载车间的生产线
                          await this.loadProductionLinesForWorkshop(workshopNode.data, true);
                          
                          // 更新视图
                          this.$nextTick(() => {
                            // 确保各节点展开
                            const root = store.nodesMap.root;
                            if (root) root.expanded = true;
                            
                            const factoryNode = store.nodesMap[factoryId];
                            if (factoryNode) factoryNode.expanded = true;
                            
                            // 确保车间节点展开
                            workshopNode.expanded = true;
                            
                            // 恢复之前的展开状态
                            expandedKeys.forEach(key => {
                              const node = store.nodesMap[key];
                              if (node) node.expanded = true;
                            });
                            
                            // 强制更新视图
                            this.$refs.tree.$forceUpdate();
                            
                            // 延迟再次刷新，确保视图完全更新
                            setTimeout(() => {
                              if (this.$refs.tree) {
                                this.$refs.tree.$forceUpdate();
                              }
                            }, 200);
                          });
                        } else {
                          // 如果找不到车间节点，完全重新加载整个树
                          console.log("未找到车间节点，重新加载整个树");
                          await this.initTreeWithLazyLoading();
                          
                          // 恢复树状态
                          this.$nextTick(() => {
                            // 确保根节点展开
                            const root = this.$refs.tree.store.nodesMap.root;
                            if (root) root.expanded = true;
                            
                            // 确保工厂节点展开
                            const factoryNode = this.$refs.tree.store.nodesMap[factoryId];
                            if (factoryNode) factoryNode.expanded = true;
                            
                            // 尝试找到并展开车间节点
                            const workshopNode = this.$refs.tree.store.nodesMap[`${factoryId}_${workshopId}`];
                            if (workshopNode) workshopNode.expanded = true;
                            
                            // 恢复其他展开状态
                            expandedKeys.forEach(key => {
                              const node = this.$refs.tree.store.nodesMap[key];
                              if (node) node.expanded = true;
                            });
                            
                            // 恢复选中状态
                            if (currentSelectedKey) {
                              this.$refs.tree.setCurrentKey(currentSelectedKey);
                            }
                          });
                        }
                      }
                    } catch (error) {
                      console.error("更新树结构失败:", error);
                      // 即使更新树失败，也不影响生产线的更新成功状态
                      // 尝试最后的方法 - 完全重新加载树
                      try {
                        await this.initTreeWithLazyLoading();
                      } catch (e) {
                        console.error("最终树重载失败:", e);
                      }
                    }
                  }
                } catch (error) {
                  console.error("更新生产线失败:", error);
                  this.$modal.msgError("修改生产线失败: " + (error.message || "未知错误"));
                  return; // 出错时返回，不关闭对话框
                }
              } else {
                // 新增生产线 - 确保工厂和车间的ID和名称都传递给后端
                const factoryId = this.form.factory_id;
                const workshopId = this.form.workshop_id;
                
                // 如果是新增模式且有生产线编号，在提交前获取真正的编号
                if (this.form.line_code) {
                  try {
                    const response = await getAutoNumbersConsume(24);
                    if (typeof response === 'string') {
                      this.form.line_code = response;
                      this.form.production_line_code = response;
                    } else if (response && response.msg) {
                      this.form.line_code = response.msg;
                      this.form.production_line_code = response.msg;
                    } else if (response && response.data) {
                      this.form.line_code = response.data;
                      this.form.production_line_code = response.data;
                    }
                  } catch (error) {
                    this.$modal.msgError('获取最终生产线编号失败');
                    return;
                  }
                }
                
                // 从映射中获取工厂和车间名称
                const factoryName = this.factoryNameMap[factoryId] || '未知工厂';
                
                // 查找车间名称 - 可能需要从当前节点或映射中获取
                let workshopName = '';
                if (this.currentNode && this.currentNode.label) {
                  workshopName = this.currentNode.label;
                } else if (this.workshopNameMap && this.workshopNameMap[workshopId]) {
                  workshopName = this.workshopNameMap[workshopId];
                } else {
                  workshopName = '未知车间';
                }
                
                // 构建包含完整信息的提交数据，字段名称与数据库字段匹配
                const lineData = {
                  // 基本信息
                  factory_id: factoryId,
                  factory_name: factoryName,
                  workshop_id: workshopId,
                  workshop_name: workshopName,
                  // 生产线信息 - 根据SQL字段名称进行匹配
                  production_line_code: this.form.line_code,
                  production_line_name: this.form.line_name,
                  // 其他信息
                  remarks: this.form.remarks,
                  is_delete: 0, // 默认为未删除
                };
                
                console.log("提交生产线数据:", lineData);
                
                try {
                  // 提交数据
                  await addProductionLine(lineData);
                  this.$modal.msgSuccess("新增生产线成功");
                  
                  // 保存当前树的展开状态和选中节点
                  let currentSelectedKey = null;
                  const expandedKeys = [];
                  
                  if (this.$refs.tree) {
                    // 获取当前选中节点
                    currentSelectedKey = this.$refs.tree.getCurrentKey();
                    
                    // 收集所有已展开节点
                    const store = this.$refs.tree.store;
                    if (store && store.nodesMap) {
                      Object.keys(store.nodesMap).forEach(key => {
                        if (store.nodesMap[key].expanded) {
                          expandedKeys.push(key);
                        }
                      });
                    }
                    console.log("保存展开节点状态:", expandedKeys);
                  }
                  
                  // 关闭对话框并清空表单，先于数据加载
                  this.open = false;
                  this.reset();
                  
                  // 延迟一段时间再加载数据，避免"数据正在处理"错误
                  await new Promise(resolve => setTimeout(resolve, 500));
                  
                  // 先刷新生产线列表
                  await this.getLineList();
                  
                  // 延迟再次加载树结构
                  await new Promise(resolve => setTimeout(resolve, 300));
                  
                  // 更新树结构
                  try {
                    // 找到对应的车间节点
                    if (this.$refs.tree && this.$refs.tree.store) {
                      // 构建车间节点的ID
                      const workshopNodeId = `${factoryId}_${workshopId}`;
                      const store = this.$refs.tree.store;
                      const workshopNode = store.nodesMap[workshopNodeId];
                      
                      if (workshopNode && workshopNode.data) {
                        console.log("找到车间节点:", workshopNode.data.label, "，重新加载生产线");
                        
                        // 强制重新加载该车间的生产线
                        await this.loadProductionLinesForWorkshop(workshopNode.data, true);
                        
                        // 更新视图
                        this.$nextTick(() => {
                          // 确保各节点展开
                          const root = store.nodesMap.root;
                          if (root) root.expanded = true;
                          
                          const factoryNode = store.nodesMap[factoryId];
                          if (factoryNode) factoryNode.expanded = true;
                          
                          // 确保车间节点展开，这样才能看到新增的生产线
                          workshopNode.expanded = true;
                          
                          // 恢复之前的展开状态
                          expandedKeys.forEach(key => {
                            const node = store.nodesMap[key];
                            if (node) node.expanded = true;
                          });
                          
                          // 选择当前车间节点
                          this.$refs.tree.setCurrentKey(workshopNodeId);
                          
                          // 强制更新视图
                          this.$refs.tree.$forceUpdate();
                          
                          // 延迟再次更新，确保视图正确
                          setTimeout(() => {
                            this.$forceUpdate();
                          }, 200);
                        });
                      } else {
                        console.warn("未找到车间节点，重新加载整个树");
                        await this.initTreeWithLazyLoading();
                        
                        // 恢复树状态
                        this.$nextTick(() => {
                          // 确保根节点展开
                          const root = this.$refs.tree.store.nodesMap.root;
                          if (root) root.expanded = true;
                          
                          // 确保工厂节点展开
                          const factoryNode = this.$refs.tree.store.nodesMap[factoryId];
                          if (factoryNode) factoryNode.expanded = true;
                          
                          // 尝试找到并展开车间节点
                          const workshopNode = this.$refs.tree.store.nodesMap[workshopNodeId];
                          if (workshopNode) workshopNode.expanded = true;
                          
                          // 恢复其他展开状态
                          expandedKeys.forEach(key => {
                            const node = this.$refs.tree.store.nodesMap[key];
                            if (node) node.expanded = true;
                          });
                          
                          // 强制更新视图
                          this.$refs.tree.$forceUpdate();
                        });
                      }
                    }
                  } catch (treeError) {
                    console.error("更新树结构失败:", treeError);
                    // 即使更新树失败，也不影响生产线的新增成功状态
                  }
                } catch (error) {
                  console.error("新增生产线失败:", error);
                  this.$modal.msgError("新增生产线失败: " + (error.message || "未知错误"));
                  return; // 出错时返回，不关闭对话框
                }
              }
            } 
            else if (this.formType === 'workstation') {
              // 工位表单提交
              if (this.form.id) {
                // 更新工位
                await updateWorkstation(this.form);
                this.$modal.msgSuccess("修改工位成功");
              } else {
                // 新增工位
                // 如果是新增模式且有工位编号，在提交前获取真正的编号
                if (this.form.station_code) {
                  try {
                    const response = await getAutoNumbersConsume(25);
                    if (typeof response === 'string') {
                      this.form.station_code = response;
                    } else if (response && response.msg) {
                      this.form.station_code = response.msg;
                    } else if (response && response.data) {
                      this.form.station_code = response.data;
                    }
                  } catch (error) {
                    this.$modal.msgError('获取最终工位编号失败');
                    return;
                  }
                }
                
                // 确保包含所有必要的字段
                const workstationData = {
                  ...this.form,
                  // 确保包含工厂信息
                  factory_id: this.form.factory_id,
                  factory_name: this.factoryNameMap[this.form.factory_id] || this.form.factory_name || '未知工厂',
                  // 确保包含车间信息
                  workshop_id: this.form.workshop_id,
                  workshop_name: this.workshopNameMap[this.form.workshop_id] || this.form.workshop_name || '未知车间',
                  // 确保包含生产线信息
                  line_id: this.form.line_id,
                  production_line_id: this.form.line_id, // 添加兼容字段
                  production_line_name: this.form.production_line_name || this.form.line_name || '未知生产线'
                };
                
                console.log("提交工位数据:", workstationData);
                await addWorkstation(workstationData);
                this.$modal.msgSuccess("新增工位成功");
              }
              // 刷新工位列表
              await this.getWorkstationList();
            }
            
            // 关闭对话框
            this.open = false;
            this.reset();
          } catch (error) {
            console.error("保存数据失败:", error);
            this.$modal.msgError("操作失败，请重试");
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let id, name, deleteFunction;
      
      if (this.currentNodeType === 'factory') {
        id = row.factory_id || this.ids;
        name = "工厂";
        deleteFunction = delFactory;
      } else if (this.currentNodeType === 'workshop') {
        id = row.workshop_id || this.ids;
        name = "车间";
        deleteFunction = delWorkshop;
      } else if (this.currentNodeType === 'line') {
        // 确保使用正确的ID字段 - 优先使用production_line_id，这是后端识别的主要字段
        id = row.production_line_id || row.line_id || row.lineId || this.ids;
        console.log("准备删除生产线，ID:", id, "行数据:", row);
        name = "生产线";
        deleteFunction = delProductionLine;
      } else if (this.currentNodeType === 'workstation') {
        id = row.station_id || this.ids;
        name = "工位";
        deleteFunction = delWorkstation;
      }
      
      this.$modal.confirm('是否确认删除' + name + '编号为"' + id + '"的数据项?').then(async () => {
        // 如果是删除工厂，先检查该工厂下是否有车间
        if (this.currentNodeType === 'factory') {
          try {
            console.log("检查工厂是否存在关联的车间:", id);
            const workshopRes = await listWorkshop({
              basicFactory: {
                factory_id: id
              },
              pageSize: 1, // 只需查询是否有数据，减轻服务器负担
              pageNum: 1
            });
            
            // 如果该工厂下有车间，提示不可删除
            if (workshopRes && workshopRes.rows && workshopRes.rows.length > 0) {
              this.$modal.msgError("该工厂下存在车间数据，不可删除！");
              return; // 终止删除操作
            }
          } catch (error) {
            console.error("检查工厂关联车间出错:", error);
            this.$modal.msgError("检查工厂数据失败，请重试");
            return; // 出错时也终止删除
          }
        }
        // 如果是删除车间，先检查该车间下是否有生产线
        else if (this.currentNodeType === 'workshop') {
          try {
            console.log("检查车间是否存在关联的生产线:", id);
            const lineRes = await listProductionLine({
              basicWorkshop: {
                workshop_id: parseInt(id)
              },
              pageSize: 1, // 只需查询是否有数据，减轻服务器负担
              pageNum: 1
            });
            
            // 如果该车间下有生产线，提示不可删除
            if (lineRes && lineRes.rows && lineRes.rows.length > 0) {
              this.$modal.msgError("该车间下存在生产线数据，不可删除！");
              return; // 终止删除操作
            }
          } catch (error) {
            console.error("检查车间关联生产线出错:", error);
            this.$modal.msgError("检查车间数据失败，请重试");
            return; // 出错时也终止删除
          }
        }
        // 如果是删除生产线，先检查该生产线下是否有工位
        else if (this.currentNodeType === 'line') {
          try {
            console.log("检查生产线是否存在关联的工位:", id);
            const workstationRes = await listWorkstation({
              basicProductionline: {
                production_line_id: parseInt(id)
              },
              pageSize: 1, // 只需查询是否有数据，减轻服务器负担
              pageNum: 1
            });
            
            // 如果该生产线下有工位，提示不可删除
            if (workstationRes && workstationRes.rows && workstationRes.rows.length > 0) {
              this.$modal.msgError("该生产线下存在工位数据，不可删除！");
              return; // 终止删除操作
            }
          } catch (error) {
            console.error("检查生产线关联工位出错:", error);
            this.$modal.msgError("检查生产线数据失败，请重试");
            return; // 出错时也终止删除
          }
        }
        
        // 通过检查，执行删除操作
        return deleteFunction(id);
      }).then(async (res) => {
        // 如果没有返回结果，说明前面终止了操作
        if (!res) return;
        
        // 保存树状态
        let currentSelectedKey = null;
        const expandedKeys = [];
        
        if (this.$refs.tree) {
          // 获取当前选中节点
          currentSelectedKey = this.$refs.tree.getCurrentKey();
          
          // 收集所有已展开节点
          const store = this.$refs.tree.store;
          if (store && store.nodesMap) {
            Object.keys(store.nodesMap).forEach(key => {
              if (store.nodesMap[key].expanded) {
                expandedKeys.push(key);
              }
            });
          }
          console.log("删除前保存展开节点状态:", expandedKeys);
        }

        if (this.currentNodeType === 'factory') {
          this.getList();
          
          // 从工厂映射中删除
          if (id && this.factoryNameMap[id]) {
            console.log("从映射中删除工厂:", id);
            delete this.factoryNameMap[id];
          }
          
          // 重新加载树结构以反映删除
          console.log("重新加载树结构...");
          await this.initTreeWithLazyLoading();
          
          // 恢复树状态
          this.$nextTick(() => {
            if (this.$refs.tree) {
              console.log("恢复树节点状态...");
              
              // 首先确保根节点展开
              const root = this.$refs.tree.store.nodesMap.root;
              if (root) root.expanded = true;
              
              // 恢复之前的展开状态，排除已删除的节点
              expandedKeys.forEach(key => {
                // 跳过被删除的工厂节点
                if (key === id) return;
                
                const node = this.$refs.tree.store.nodesMap[key];
                if (node) {
                  node.expanded = true;
                }
              });
              
              // 如果当前选中的节点被删除了，选择根节点
              if (currentSelectedKey && currentSelectedKey !== id) {
                this.$refs.tree.setCurrentKey(currentSelectedKey);
              } else {
                this.$refs.tree.setCurrentKey('root');
              }
            }
          });
        } else if (this.currentNodeType === 'workshop') {
          // 刷新车间列表
          await this.getWorkshopList();
          
          // 从车间映射中删除
          if (id && this.workshopNameMap[id]) {
            console.log("从映射中删除车间:", id);
            delete this.workshopNameMap[id];
          }
          
          // 使用更可靠的方法重新加载整个树结构
          console.log("重新加载树结构以反映车间删除...");
          try {
            // 确定当前工厂ID，可能需要从多个来源获取
            let factoryId = null;
            if (this.currentNode && this.currentNode.factoryId) {
              factoryId = this.currentNode.factoryId;
            } else if (this.queryParams && (this.queryParams.factoryId || this.queryParams.factory_id)) {
              factoryId = this.queryParams.factoryId || this.queryParams.factory_id;
            }
            
            // 保存重要的展开状态和选中节点
            let currentSelectedKey = null;
            const expandedKeys = [];
            
            if (this.$refs.tree) {
              // 获取当前选中节点
              currentSelectedKey = this.$refs.tree.getCurrentKey();
              
              // 收集所有已展开节点
              const store = this.$refs.tree.store;
              if (store && store.nodesMap) {
                Object.keys(store.nodesMap).forEach(key => {
                  if (store.nodesMap[key].expanded) {
                    expandedKeys.push(key);
                  }
                });
              }
              console.log("车间删除 - 保存展开节点状态:", expandedKeys);
            }
            
            // 完全重新加载树结构 - 这是确保删除后视图一致的最可靠方法
            await this.loadFactoryNameMap(); // 重新加载工厂映射
            await this.loadWorkshopNameMap(); // 重新加载车间映射
            await this.initTreeWithLazyLoading(); // 重建整个树结构
            
            // 恢复树状态
            this.$nextTick(() => {
              if (this.$refs.tree) {
                console.log("恢复树节点状态...");
                
                // 首先确保根节点展开
                const root = this.$refs.tree.store.nodesMap.root;
                if (root) root.expanded = true;
                
                // 确保工厂节点展开
                if (factoryId) {
                  const factoryNode = this.$refs.tree.store.nodesMap[factoryId];
                  if (factoryNode) {
                    factoryNode.expanded = true;
                    console.log("已展开工厂节点:", factoryId);
                  }
                }
                
                // 恢复之前的展开状态，排除已删除的节点
                expandedKeys.forEach(key => {
                  // 如果节点ID包含被删除车间的ID，则跳过
                  if (key.includes(`_${id}`) || key === id) return;
                  
                  const node = this.$refs.tree.store.nodesMap[key];
                  if (node) {
                    node.expanded = true;
                  }
                });
                
                // 选择合适的节点
                if (currentSelectedKey && (currentSelectedKey.includes(`_${id}`) || currentSelectedKey === id)) {
                  // 如果当前选中的节点是被删除的车间，选择工厂节点或根节点
                  if (factoryId) {
                    this.$refs.tree.setCurrentKey(factoryId);
                  } else {
                    this.$refs.tree.setCurrentKey('root');
                  }
                } else if (currentSelectedKey) {
                  // 保留原有的选中节点
                  this.$refs.tree.setCurrentKey(currentSelectedKey);
                }
                
                // 强制更新树视图
                this.$refs.tree.$forceUpdate();
                
                // 再次强制更新，确保视图反映最新数据
                setTimeout(() => {
                  if (this.$refs.tree) {
                    this.$refs.tree.$forceUpdate();
                  }
                }, 200);
              }
            });
          } catch (error) {
            console.error("更新树结构失败:", error);
            this.$message.error("更新视图失败，请刷新页面");
          }
        } else if (this.currentNodeType === 'line') {
          // 先刷新生产线列表
          await this.getLineList();
          
          // 获取当前生产线所属的工厂和车间ID
          let factoryId = null;
          let workshopId = null;
          
          // 尝试从不同来源获取工厂和车间ID
          if (this.currentNode) {
            factoryId = this.currentNode.factoryId || null;
            workshopId = this.currentNode.workshopId || null;
          }
          
          if (!factoryId && this.queryParams) {
            factoryId = this.queryParams.factoryId || this.queryParams.factory_id || null;
          }
          
          if (!workshopId && this.queryParams) {
            workshopId = this.queryParams.workshopId || this.queryParams.workshop_id || null;
          }
          
          // 如果是从行数据中获取，可能需要从row参数获取
          if (row && (!factoryId || !workshopId)) {
            factoryId = row.factory_id || factoryId;
            workshopId = row.workshop_id || workshopId;
          }
          
          console.log("删除生产线后更新树视图，工厂ID:", factoryId, "车间ID:", workshopId);
          
          if (factoryId && workshopId) {
            try {
              // 查找对应的车间节点
              if (this.$refs.tree && this.$refs.tree.store) {
                const workshopNodeId = `${factoryId}_${workshopId}`;
                const store = this.$refs.tree.store;
                const workshopNode = store.nodesMap[workshopNodeId];
                
                if (workshopNode && workshopNode.data) {
                  console.log("找到车间节点:", workshopNode.data.label, "，重新加载生产线");
                  
                  // 清空车间节点的子节点（生产线）
                  if (workshopNode.data.children) {
                    workshopNode.data.children = [];
                  }
                  workshopNode.childNodes = [];
                  
                  // 设置为未加载状态，确保重新加载
                  workshopNode.data.loaded = false;
                  
                  // 强制重新加载该车间的生产线
                  await this.loadProductionLinesForWorkshop(workshopNode.data, true);
                  
                  // 更新视图
                  this.$nextTick(() => {
                    // 确保各节点展开状态保持不变
                    expandedKeys.forEach(key => {
                      // 如果是被删除的生产线，则跳过
                      if (key.includes(`_${id}`) || key === id) return;
                      
                      const node = store.nodesMap[key];
                      if (node) {
                        node.expanded = true;
                      }
                    });
                    
                    // 确保车间节点始终展开，以便看到更新后的生产线列表
                    workshopNode.expanded = true;
                    
                    // 如果当前选中的是被删除的节点，则选择其父节点
                    if (currentSelectedKey && (currentSelectedKey.includes(`_${id}`) || currentSelectedKey === id)) {
                      this.$refs.tree.setCurrentKey(workshopNodeId);
                    } else if (currentSelectedKey) {
                      this.$refs.tree.setCurrentKey(currentSelectedKey);
                    }
                    
                    // 强制更新视图
                    this.$refs.tree.$forceUpdate();
                    
                    // 确保视图更新
                    setTimeout(() => {
                      if (this.$refs.tree) {
                        this.$refs.tree.$forceUpdate();
                      }
                    }, 200);
                  });
                } else {
                  // 如果找不到车间节点，尝试重新加载整个树结构
                  console.log("未找到车间节点，重新加载整个树结构");
                  await this.initTreeWithLazyLoading();
                  
                  // 恢复树状态
                  this.$nextTick(() => {
                    // 确保根节点展开
                    const root = this.$refs.tree.store.nodesMap.root;
                    if (root) root.expanded = true;
                    
                    // 恢复展开状态，排除已删除节点
                    expandedKeys.forEach(key => {
                      if (key.includes(`_${id}`) || key === id) return;
                      const node = this.$refs.tree.store.nodesMap[key];
                      if (node) node.expanded = true;
                    });
                    
                    // 选择合适的节点
                    if (currentSelectedKey && (currentSelectedKey.includes(`_${id}`) || currentSelectedKey === id)) {
                      const newNodeId = `${factoryId}_${workshopId}`;
                      if (this.$refs.tree.store.nodesMap[newNodeId]) {
                        this.$refs.tree.setCurrentKey(newNodeId);
                      } else {
                        this.$refs.tree.setCurrentKey(factoryId);
                      }
                    } else if (currentSelectedKey) {
                      this.$refs.tree.setCurrentKey(currentSelectedKey);
                    }
                  });
                }
              }
            } catch (error) {
              console.error("删除生产线后更新树视图失败:", error);
              // 如果更新失败，尝试重新加载整个树
              try {
                await this.initTreeWithLazyLoading();
              } catch (e) {
                console.error("最后的树重载失败:", e);
              }
            }
          }
        } else if (this.currentNodeType === 'workstation') {
          this.getWorkstationList();
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        // 这里捕获所有取消删除和删除失败的情况
      });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    
    /** 获取自动编号 */
    handleGetAutoNumber() {
      // 如果是编辑模式且已有工厂编号，则不重新获取
      if (this.form.factory_id && this.form.factory_code) {
        console.log("编辑模式，保留原工厂编号:", this.form.factory_code);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为22（工厂编号）
      getAutoNumbers(22).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.factory_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.factory_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.factory_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.factory_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.factory_code = "F" + new Date().getTime().toString().substring(6); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },

    /** 树节点展开事件 */
    async handleNodeExpand(data, node) {
      // 防止重复加载
      if (data.loaded) {
        console.log(`节点[${data.label}]已加载子节点，跳过`);
        return;
      }
      
      // 显示加载状态
      this.loading = true;
      
      try {
        if (data.type === 'factory') {
          // 当工厂节点展开时，加载该工厂下的车间
          console.log(`展开工厂节点[${data.label}]，加载车间`);
          await this.loadWorkshopsForFactory(data);
          data.loaded = true;
          
          // 为每个车间预加载生产线
          for (const workshopNode of data.children) {
            await this.loadProductionLinesForWorkshop(workshopNode);
          }
        } else if (data.type === 'workshop') {
          // 当车间节点展开时，加载该车间下的生产线
          console.log(`展开车间节点[${data.label}]，加载生产线`);
          await this.loadProductionLinesForWorkshop(data);
          data.loaded = true;
        }
        
        // 强制更新树视图
        this.$nextTick(() => {
          this.$refs.tree.updateKeyChildren(data.id, data.children);
        });
      } catch (error) {
        console.error(`加载节点[${data.label}]的子节点失败:`, error);
      } finally {
        this.loading = false;
      }
    },

    /** 树节点折叠事件 */
    async handleNodeCollapse(data, node) {
      // 处理树节点折叠的逻辑
      console.log(`折叠节点[${data.label}]`);
    },
    
    /** 获取车间自动编号 */
    handleGetAutoWorkshopNumber() {
      // 如果是编辑模式且已有车间编号，则不重新获取
      if (this.form.workshop_id && this.form.workshop_code) {
        console.log("编辑模式，保留原车间编号:", this.form.workshop_code);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为23（车间编号）
      getAutoNumbers(23).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.workshop_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.workshop_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.workshop_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.workshop_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.workshop_code = "W" + new Date().getTime().toString().substring(6); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },

    /** 获取生产线自动编号 */
    handleGetAutoLineNumber() {
      // 如果是编辑模式且已有生产线编号，则不重新获取
      if (this.form.line_id && this.form.line_code) {
        console.log("编辑模式，保留原生产线编号:", this.form.line_code);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为24（生产线编号）
      getAutoNumbers(24).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.line_code = response;
          // 同时设置production_line_code字段，确保后端识别
          this.form.production_line_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.line_code = response.data;
            this.form.production_line_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.line_code = response.msg;
            this.form.production_line_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.line_code = response.rows[0];
            this.form.production_line_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.line_code = "L" + new Date().getTime().toString().substring(6); // 生成临时编号
            this.form.production_line_code = this.form.line_code;
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    },

    /** 获取工位自动编号 */
    handleGetAutoStationNumber() {
      // 如果是编辑模式且已有工位编号，则不重新获取
      if (this.form.station_id && this.form.station_code) {
        console.log("编辑模式，保留原工位编号:", this.form.station_code);
        return;
      }
      
      this.$modal.loading("正在获取自动编码...");
      
      // 调用获取自动编码接口，传入编码类型参数值为25（工位编号）
      getAutoNumbers(25).then(response => {
        this.$modal.closeLoading();
        
        console.log("自动编码API返回数据:", response);
        
        // 检查各种可能的返回格式
        if (typeof response === 'string') {
          // 直接返回字符串编号
          this.form.station_code = response;
          return;
        }
        
        if (response === null || response === undefined) {
          this.$modal.msgError("获取自动编号失败：返回为空");
          return;
        }
        
        // 检查常见的接口返回格式
        if (response.code === 200 || response.code === 0) {
          // 标准若依框架返回格式
          if (response.data) {
            this.form.station_code = response.data;
          } else if (response.msg && typeof response.msg === 'string') {
            this.form.station_code = response.msg;
          } else if (response.rows && response.rows.length > 0) {
            this.form.station_code = response.rows[0];
          } else {
            // 无法从标准字段获取，尝试直接读取
            console.warn("无法从标准返回字段获取编号，尝试直接读取response");
            this.form.station_code = "S" + new Date().getTime().toString().substring(6); // 生成临时编号
          }
        } else {
          console.error("获取自动编号失败，响应：", response);
          this.$modal.msgError("获取自动编号失败：" + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.$modal.closeLoading();
        console.error("获取自动编号失败:", error);
        this.$modal.msgError("获取自动编号失败: " + (error.message || "未知错误"));
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.tree-container {
  margin-top: 10px;
  height: calc(100vh - 200px);
  overflow: auto;
  border: 1px solid #e5e6e7;
  background-color: #f0f3f8;
  padding: 0;
  border-radius: 2px;
}

.tree-container .el-tree {
  background-color: transparent;
}

.head-container {
  margin-bottom: 10px;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #f5f7fa !important;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 树节点样式调整 */
::v-deep .el-tree-node__expand-icon {
  font-size: 16px;
  color: #606266;
}

::v-deep .el-tree-node__content {
  height: 32px;
  line-height: 32px;
}

::v-deep .el-tree-node__expand-icon.expanded {
  transform: rotate(90deg);
}

::v-deep .el-tree-node__expand-icon.is-leaf {
  color: transparent;
}

/* 工厂树样式 - 匹配图片中的样式 */
.factory-tree {
  font-size: 14px;
  background-color: #f0f3f8;
}

::v-deep .factory-tree .el-tree-node__content {
  height: 32px;
  line-height: 32px;
  padding-left: 8px;
}

::v-deep .factory-tree .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e6f1fc !important;
}

/* 展开箭头样式 */
::v-deep .factory-tree .el-tree-node__expand-icon {
  color: #606266;
  font-size: 14px;
  padding: 6px;
}

::v-deep .factory-tree .el-tree-node__expand-icon.expanded {
  transform: rotate(90deg);
}

/* 根节点样式 */
::v-deep .factory-tree .el-tree-node:first-child > .el-tree-node__content {
  background-color: #f0f3f8;
  font-weight: bold;
}

/* 树节点图标样式 */
.custom-tree-node i {
  margin-right: 5px;
  font-size: 16px;
  vertical-align: middle;
}

.custom-tree-node i.el-icon-s-fold {
  color: #606266;
}

.custom-tree-node i.el-icon-document {
  color: #409EFF;
}

.custom-tree-node i.el-icon-house {
  color: #67C23A;
}

.custom-tree-node i.el-icon-s-operation {
  color: #E6A23C;
}

/* 确保备注和创建人列正确显示 */
::v-deep .el-table .cell {
  word-break: break-word;
  line-height: 20px;
}

/* 隐藏创建人列中的按钮 */
::v-deep .creator-column .el-button,
::v-deep .el-table td.el-table_1_column_7 .el-button,
::v-deep .el-table td:nth-last-child(2) .el-button {
  display: none !important;
}

/* 确保创建人列不显示任何操作按钮 */
::v-deep .creator-column .cell {
  overflow: visible;
}

/* 确保操作列按钮正确显示 */
::v-deep .operation-column .el-button {
  display: inline-block !important;
}

/* 按钮颜色 */
::v-deep .blue-text {
  color: #409EFF;
}

::v-deep .red-text {
  color: #F56C6C;
}

/* 表格样式 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
}

::v-deep .el-table--border th, ::v-deep .el-table--border td {
  border-right: 1px solid #EBEEF5;
}

::v-deep .el-table td {
  padding: 8px 0;
}

.factory-code-input {
  width: 100%;
}

.workshop-code-input {
  width: 100%;
}

.line-code-input {
  width: 100%;
}

.station-code-input {
  width: 100%;
}
</style>
